效果
封装组件
<template>
<div ref="container" class="scroll-area">
<div
ref="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% {
left: 0%;
transform: translateX(-100%); // 末端从左边滚出
}
}
@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-label
content="滚动内容滚动内容滚动内容滚动内容滚动内容滚动内容滚动内容"
font-color="#0091fa"
></marquee-label>
</div>
可改进处
按字数计算速度,但是没考虑到“汉字”、“字母”、“特殊字符”等所占宽度不同,如果需要速度不变的话可优化