vue实现文字播放栏
Vue 实现文字播放栏
文字播放栏(也称为跑马灯或滚动字幕)是一种常见的 UI 效果,用于展示动态滚动的文本内容。以下是几种实现方式:
使用 CSS 动画实现
通过 CSS 的 animation 和 @keyframes 实现文本滚动效果。
<template>
<div class="marquee-container">
<div class="marquee-text">{{ text }}</div>
</div>
</template>
<script>
export default {
data() {
return {
text: "这里是需要滚动的文字内容,可以根据需求动态更新。"
};
}
};
</script>
<style>
.marquee-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.marquee-text {
display: inline-block;
animation: marquee 10s linear infinite;
}
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
使用 Vue 动态计算位置
通过 Vue 的数据绑定和 setInterval 动态更新文本位置。
<template>
<div class="marquee-container" ref="container">
<div
class="marquee-text"
:style="{ transform: `translateX(${position}px)` }"
>
{{ text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
text: "动态计算的滚动文字效果",
position: 0,
speed: 2,
containerWidth: 0,
textWidth: 0
};
},
mounted() {
this.containerWidth = this.$refs.container.offsetWidth;
this.textWidth = this.$refs.container.querySelector('.marquee-text').offsetWidth;
this.startAnimation();
},
methods: {
startAnimation() {
setInterval(() => {
this.position -= this.speed;
if (this.position < -this.textWidth) {
this.position = this.containerWidth;
}
}, 16);
}
}
};
</script>
<style>
.marquee-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
position: relative;
}
.marquee-text {
display: inline-block;
position: absolute;
white-space: nowrap;
}
</style>
使用第三方库
如果需要更复杂的功能(如暂停、反向滚动),可以使用第三方库如 vue-marquee-text-component。
安装:
npm install vue-marquee-text-component
使用:
<template>
<marquee-text :duration="10" :repeat="4">
{{ text }}
</marquee-text>
</template>
<script>
import MarqueeText from 'vue-marquee-text-component';
export default {
components: {
MarqueeText
},
data() {
return {
text: "使用第三方库实现的滚动文字效果"
};
}
};
</script>
自定义指令实现
通过 Vue 自定义指令封装滚动逻辑,方便复用。

<template>
<div v-marquee="{ speed: 3 }">{{ text }}</div>
</template>
<script>
export default {
data() {
return {
text: "自定义指令实现的滚动文字"
};
},
directives: {
marquee: {
inserted(el, binding) {
const speed = binding.value.speed || 2;
let position = 0;
const textWidth = el.offsetWidth;
const containerWidth = el.parentNode.offsetWidth;
function animate() {
position -= speed;
if (position < -textWidth) {
position = containerWidth;
}
el.style.transform = `translateX(${position}px)`;
requestAnimationFrame(animate);
}
animate();
}
}
}
};
</script>
<style>
[v-marquee] {
display: inline-block;
white-space: nowrap;
overflow: hidden;
}
</style>
以上方法可以根据项目需求选择,CSS 动画适合简单场景,动态计算和自定义指令更灵活,第三方库适合快速集成复杂功能。






