Vue实现滚动字幕
Vue实现滚动字幕的方法
使用CSS动画实现
通过CSS的@keyframes和transform属性实现水平滚动效果,结合Vue的动态绑定控制内容。
<template>
<div class="scroll-container">
<div class="scroll-text" :style="{ animationDuration: duration + 's' }">
{{ text }}
</div>
</div>
</template>
<script>
export default {
props: {
text: String,
duration: {
type: Number,
default: 10
}
}
};
</script>
<style>
.scroll-container {
overflow: hidden;
white-space: nowrap;
width: 100%;
}
.scroll-text {
display: inline-block;
animation: scroll linear infinite;
}
@keyframes scroll {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
使用JavaScript动态计算
通过requestAnimationFrame实现更精确的滚动控制,适合需要暂停或交互的场景。
<template>
<div class="scroll-container" ref="container">
<div class="scroll-text" ref="text" :style="{ left: position + 'px' }">
{{ text }}
</div>
</div>
</template>
<script>
export default {
props: {
text: String,
speed: {
type: Number,
default: 1
}
},
data() {
return {
position: 0,
animationId: null
};
},
mounted() {
this.startScroll();
},
beforeDestroy() {
cancelAnimationFrame(this.animationId);
},
methods: {
startScroll() {
const containerWidth = this.$refs.container.offsetWidth;
const textWidth = this.$refs.text.offsetWidth;
const animate = () => {
this.position -= this.speed;
if (this.position < -textWidth) {
this.position = containerWidth;
}
this.animationId = requestAnimationFrame(animate);
};
animate();
}
}
};
</script>
<style>
.scroll-container {
position: relative;
overflow: hidden;
white-space: nowrap;
width: 100%;
height: 1.2em;
}
.scroll-text {
position: absolute;
}
</style>
使用第三方库(如vue-marquee)
对于复杂需求,可直接使用现成的Vue组件库简化开发。
安装依赖:
npm install vue-marquee-text-component
示例代码:
<template>
<vue-marquee :duration="duration" :repeat="repeat">
{{ text }}
</vue-marquee>
</template>
<script>
import VueMarquee from 'vue-marquee-text-component';
export default {
components: { VueMarquee },
props: {
text: String,
duration: {
type: Number,
default: 10
},
repeat: {
type: Number,
default: 4
}
}
};
</script>
注意事项
- 动态内容需考虑容器宽度与文本长度的适配,避免滚动不连贯。
- 移动端性能优化可考虑使用
will-change: transform提升渲染效率。 - 需要暂停功能时,CSS方案可通过动态添加
animation-play-state: paused实现。
以上方案可根据实际需求选择,CSS动画适合简单场景,JavaScript控制更灵活,第三方库能快速实现复杂效果。






