vue简单实现无缝滚动
vue实现无缝滚动的核心方法
基于CSS动画实现
通过CSS的@keyframes定义动画,结合transform: translateY实现垂直滚动效果。动画设置为无限循环,通过调整animation-duration控制速度。
<template>
<div class="scroll-container">
<div class="scroll-content">
<!-- 双份相同内容实现无缝衔接 -->
<div v-for="(item, index) in list" :key="index">{{item}}</div>
<div v-for="(item, index) in list" :key="index+list.length">{{item}}</div>
</div>
</div>
</template>
<style>
.scroll-container {
height: 200px;
overflow: hidden;
}
.scroll-content {
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0% { transform: translateY(0); }
100% { transform: translateY(-50%); }
}
</style>
使用requestAnimationFrame动态计算 通过JavaScript动态计算位置实现更精确的控制,适合需要暂停/继续的场景。

export default {
data() {
return {
list: ['内容1', '内容2', '内容3'],
currentPosition: 0,
timer: null
}
},
mounted() {
this.startScroll()
},
methods: {
startScroll() {
const containerHeight = this.$el.clientHeight
const contentHeight = this.$el.querySelector('.content').clientHeight
const step = () => {
this.currentPosition -= 1
if (Math.abs(this.currentPosition) >= contentHeight/2) {
this.currentPosition = 0
}
this.$el.querySelector('.content').style.transform =
`translateY(${this.currentPosition}px)`
this.timer = requestAnimationFrame(step)
}
this.timer = requestAnimationFrame(step)
},
stopScroll() {
cancelAnimationFrame(this.timer)
}
}
}
实现水平无缝滚动
修改CSS动画的X轴平移即可实现水平滚动效果:
@keyframes horizontal-scroll {
0% { transform: translateX(0); }
100% { transform: translateX(-50%); }
}
性能优化建议
- 使用
will-change: transform提升动画性能 - 避免在滚动元素上使用复杂的阴影和滤镜效果
- 对移动端设备适当降低滚动速度
- 使用
transform代替top/left定位
常见问题处理
内容抖动问题
确保容器高度固定,且与内容高度成整数倍关系。添加backface-visibility: hidden可避免部分浏览器渲染问题。

暂停后继续滚动
保留最后的位置状态,继续动画时从该位置开始计算。动态调整animation-delay可实现平滑恢复。
动态内容更新 监听数据变化时重置动画:
watch: {
list() {
this.$nextTick(() => {
// 重新计算位置或重启动画
})
}
}






