vue实现无缝marquee
Vue 实现无缝 Marquee 效果
在 Vue 中实现无缝 Marquee(跑马灯)效果可以通过多种方式完成,以下是几种常见的方法:
使用 CSS 动画实现
通过 CSS 的 @keyframes 和 animation 属性可以实现简单的无缝滚动效果。这种方法性能较好,适合纯文本或简单内容的滚动。
<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>
使用 JavaScript 动态更新内容
对于更复杂的内容或需要动态更新的情况,可以使用 JavaScript 动态计算和更新内容位置。

<template>
<div class="marquee-container" ref="container">
<div class="marquee-content" ref="content">
{{ text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
text: '这是一段需要无缝滚动的文本内容。',
position: 0,
animationId: null
}
},
mounted() {
this.startAnimation()
},
beforeDestroy() {
cancelAnimationFrame(this.animationId)
},
methods: {
startAnimation() {
const containerWidth = this.$refs.container.offsetWidth
const contentWidth = this.$refs.content.offsetWidth
const animate = () => {
this.position -= 1
if (this.position <= -contentWidth) {
this.position = containerWidth
}
this.$refs.content.style.transform = `translateX(${this.position}px)`
this.animationId = requestAnimationFrame(animate)
}
animate()
}
}
}
</script>
<style>
.marquee-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.marquee-content {
display: inline-block;
}
</style>
使用第三方库
如果需要更复杂的功能或更好的性能,可以考虑使用第三方库如 vue-marquee-text-component。
安装:

npm install vue-marquee-text-component
使用:
<template>
<marquee-text :duration="10" :repeat="Infinity">
{{ text }}
</marquee-text>
</template>
<script>
import MarqueeText from 'vue-marquee-text-component'
export default {
components: {
MarqueeText
},
data() {
return {
text: '这是一段需要无缝滚动的文本内容。'
}
}
}
</script>
实现双向无缝滚动
如果需要内容在容器内双向无缝滚动,可以通过复制内容并交替显示实现。
<template>
<div class="marquee-container">
<div class="marquee-content" :style="{ transform: `translateX(${position}px)` }">
{{ text }} {{ text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
text: '这是一段需要无缝滚动的文本内容。',
position: 0,
animationId: null
}
},
mounted() {
this.startAnimation()
},
beforeDestroy() {
cancelAnimationFrame(this.animationId)
},
methods: {
startAnimation() {
const animate = () => {
this.position -= 1
if (this.position <= -this.$el.offsetWidth) {
this.position = 0
}
this.animationId = requestAnimationFrame(animate)
}
animate()
}
}
}
</script>
<style>
.marquee-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.marquee-content {
display: inline-block;
}
</style>
以上方法可以根据具体需求选择适合的实现方式。CSS 动画适合简单场景,JavaScript 实现更灵活,第三方库则提供更多功能。






