单行自动横向滚动——css实现

编程入门 行业动态 更新时间:2024-10-05 09:29:18

单行自动<a href=https://www.elefans.com/category/jswz/34/1768009.html style=横向滚动——css实现"/>

单行自动横向滚动——css实现

效果

封装组件

<template><div ref="container" class="scroll-area"><divref="content":class="[isScroll ? 'scroll' : 'no-scroll']":style="{ color: fontColor }">{{ content }}</div></div>
</template>
.scroll-area {position: relative;width: 100%;height: 100%;overflow: hidden;display: flex;align-items: center;justify-content: center;
}.scroll {position: absolute;line-height: normal;height: fit-content;white-space: nowrap;animation: todayScroll linear infinite;animation-delay: 0s;
}.no-scroll {line-height: normal;width: fit-content;height: fit-content;-ms-text-overflow: ellipsis;text-overflow: ellipsis;overflow: hidden;white-space: nowrap;max-lines: 1;
}@-webkit-keyframes todayScroll {0% {left: 100%; // 首端从右边滚入}100% {-webkit-transform: translate(-100%, 0, 0); // 末端从左边滚出}
}@keyframes todayScroll {0% {left: 100%;}100% {left: 0%;transform: translateX(-100%);}
}
export default {name: 'scrollLine',props: {content: String,minCount: {type: Number,default: 0},fontColor: {type: String,default: 'black'}},data() {return {isScroll: false}},mounted() {if ((this.minCount > 0 && this.content.length > this.minCount) || this.scrollHandler()) {this.isScroll = true;this.$nextTick(() => {const scrollElements = document.getElementsByClassName('scroll');if (scrollElements && scrollElements[0]) {const time = parseInt(this.content.length / 4) // 按字数计算滚动一次的时间,以控制速度scrollElements[0].style.setProperty('animation-duration', `${time}s`)}})}},methods: {scrollHandler() {if (this.$refs.container && this.$refs.content) {const containerWidth = this.$refs.container.clientWidth;const contentWidth = this.$refs.content.clientWidth;if (containerWidth && contentWidth && contentWidth >= containerWidth) {return true;}} else {return false;}}}
};

调用

<div style="height: 44px; background: #cdebff"><marquee-labelcontent="滚动内容滚动内容滚动内容滚动内容滚动内容滚动内容滚动内容"font-color="#0091fa"></marquee-label>
</div>

可改进处

按字数计算速度,但是没考虑到“汉字”、“字母”、“特殊字符”等所占宽度不同,如果需要速度不变的话可优化

更多推荐

单行自动横向滚动——css实现

本文发布于:2023-11-16 22:32:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634808.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:横向   css

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!