vue实现无缝marquee
Vue 实现无缝 Marquee 效果
使用 CSS3 Animation
通过 CSS3 的 animation 和 @keyframes 实现无缝滚动效果,适用于简单的文字或内容滚动。
<template>
<div class="marquee-container">
<div class="marquee-content">{{ text }}</div>
</div>
</template>
<script>
export default {
data() {
return {
text: '这是一段需要无缝滚动的文本内容,可以根据需求调整长度。'
}
}
}
</script>
<style>
.marquee-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.marquee-content {
display: inline-block;
animation: marquee 10s linear infinite;
}
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
使用 Vue 动态计算
动态计算内容宽度,实现更精确的无缝滚动,适用于内容长度不固定的情况。
<template>
<div class="marquee-wrapper" ref="wrapper">
<div class="marquee-content" ref="content" :style="contentStyle">
{{ text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
text: '动态计算宽度的无缝滚动内容',
contentWidth: 0,
wrapperWidth: 0,
duration: 10,
contentStyle: {}
}
},
mounted() {
this.calculateWidth()
this.startAnimation()
window.addEventListener('resize', this.calculateWidth)
},
beforeDestroy() {
window.removeEventListener('resize', this.calculateWidth)
},
methods: {
calculateWidth() {
this.wrapperWidth = this.$refs.wrapper.offsetWidth
this.contentWidth = this.$refs.content.offsetWidth
this.contentStyle = {
animationDuration: `${this.duration}s`,
transform: `translateX(${this.wrapperWidth}px)`
}
},
startAnimation() {
this.contentStyle = {
...this.contentStyle,
animation: `marquee ${this.duration}s linear infinite`
}
}
}
}
</script>
<style>
.marquee-wrapper {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.marquee-content {
display: inline-block;
}
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
使用第三方库 vue-marquee-text-component
对于更复杂的需求,可以使用专门的无缝滚动 Vue 组件。
安装依赖:
npm install vue-marquee-text-component
使用示例:

<template>
<marquee-text :duration="duration" :repeat="repeat">
{{ text }}
</marquee-text>
</template>
<script>
import MarqueeText from 'vue-marquee-text-component'
export default {
components: {
MarqueeText
},
data() {
return {
text: '使用第三方库实现的无缝滚动效果',
duration: 15,
repeat: 4
}
}
}
</script>
注意事项
- 确保容器有明确的宽度限制,否则滚动效果可能不正常
- 对于动态内容,需要在内容更新后重新计算宽度
- 移动端设备可能需要调整动画持续时间以获得更好的用户体验
- 考虑性能影响,特别是对于大量内容的滚动场景
以上方法可以根据具体需求选择使用,CSS3 Animation 适合简单场景,动态计算适合精确控制,第三方库则提供了更多配置选项和功能。






