vue实现文字播放栏
Vue 实现文字播放栏(跑马灯效果)
方法一:使用 CSS 动画 + Vue 数据绑定
通过 CSS 的 @keyframes 实现动画效果,结合 Vue 的动态数据绑定控制内容。
<template>
<div class="marquee-container">
<div class="marquee-content" :style="{ animationDuration: duration + 's' }">
{{ text }}
</div>
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
default: '这是滚动文字内容'
},
duration: {
type: Number,
default: 10
}
}
}
</script>
<style>
.marquee-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.marquee-content {
display: inline-block;
animation: marquee linear infinite;
}
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
方法二:纯 Vue 实现(动态计算位置)
通过 Vue 的响应式数据和计算属性动态计算位置,实现更灵活的控制。
<template>
<div class="marquee" ref="container">
<div
class="marquee-text"
:style="{ transform: `translateX(${position}px)` }"
>
{{ text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
position: 0,
containerWidth: 0,
textWidth: 0,
speed: 2,
animationId: null
}
},
props: {
text: String
},
mounted() {
this.initSizes()
this.startAnimation()
window.addEventListener('resize', this.initSizes)
},
beforeDestroy() {
cancelAnimationFrame(this.animationId)
window.removeEventListener('resize', this.initSizes)
},
methods: {
initSizes() {
this.containerWidth = this.$refs.container.offsetWidth
const tempSpan = document.createElement('span')
tempSpan.style.visibility = 'hidden'
tempSpan.style.whiteSpace = 'nowrap'
tempSpan.innerText = this.text
document.body.appendChild(tempSpan)
this.textWidth = tempSpan.offsetWidth
document.body.removeChild(tempSpan)
},
startAnimation() {
const animate = () => {
this.position -= this.speed
if (this.position < -this.textWidth) {
this.position = this.containerWidth
}
this.animationId = requestAnimationFrame(animate)
}
animate()
}
}
}
</script>
<style>
.marquee {
width: 100%;
overflow: hidden;
position: relative;
height: 1.2em;
}
.marquee-text {
position: absolute;
white-space: nowrap;
}
</style>
方法三:使用第三方库(vue-marquee-text-component)
安装 marquee 组件库可以快速实现:
npm install vue-marquee-text-component
使用示例:
<template>
<marquee-text :duration="5" :repeat="3">
这是要滚动的文字内容
</marquee-text>
</template>
<script>
import MarqueeText from 'vue-marquee-text-component'
export default {
components: {
MarqueeText
}
}
</script>
自定义功能扩展
-
添加暂停/继续功能:
// 在方法二中增加 methods: { toggleMarquee() { if (this.animationId) { cancelAnimationFrame(this.animationId) this.animationId = null } else { this.startAnimation() } } } -
支持多行文字轮播:
<template> <div class="multi-marquee"> <transition-group name="marquee" tag="div"> <div v-for="(item, index) in items" :key="index"> {{ item }} </div> </transition-group> </div> </template>
注意事项
- 性能优化:对于长文本或高频更新,建议使用 CSS 动画而非 JavaScript 计算
- 响应式处理:在窗口大小变化时重新计算容器和文本宽度
- 移动端适配:适当调整动画速度和持续时间
- 无障碍访问:为动态内容添加 ARIA 属性
以上方案可根据实际需求选择,CSS 方案性能最佳,纯 Vue 方案灵活性最强,第三方库方案最便捷。







