当前位置:首页 > VUE

vue简单实现无缝滚动

2026-02-25 04:33:08VUE

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动态计算位置实现更精确的控制,适合需要暂停/继续的场景。

vue简单实现无缝滚动

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可避免部分浏览器渲染问题。

vue简单实现无缝滚动

暂停后继续滚动 保留最后的位置状态,继续动画时从该位置开始计算。动态调整animation-delay可实现平滑恢复。

动态内容更新 监听数据变化时重置动画:

watch: {
  list() {
    this.$nextTick(() => {
      // 重新计算位置或重启动画
    })
  }
}

标签: 简单vue
分享给朋友:

相关文章

vue实现文字播放栏

vue实现文字播放栏

Vue 实现文字播放栏(跑马灯效果) 方法一:使用 CSS 动画 + Vue 数据绑定 通过 CSS 的 @keyframes 实现动画效果,结合 Vue 的动态数据绑定控制内容。 <tem…

vue实现防抖节流

vue实现防抖节流

Vue 中实现防抖(Debounce) 防抖的核心是延迟执行函数,在连续触发时取消前一次的调用,只执行最后一次。适用于输入框搜索、窗口大小调整等场景。 方法1:使用 Lodash 的 _.debou…

vue实现a

vue实现a

Vue 实现 A 功能的方法 在 Vue 中实现 A 功能可以通过多种方式,具体取决于 A 功能的具体需求。以下是几种常见的实现方法: 使用 Vue 组件 通过创建自定义组件来实现 A 功能。组件可…

vue实现图集

vue实现图集

Vue 实现图集的方法 在 Vue 中实现图集功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用第三方库(如 vue-image-lightbox) 安装 vue-image-ligh…

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基础…

vue实现翻译

vue实现翻译

Vue 实现翻译功能的方法 使用 i18n 插件实现多语言切换 安装 vue-i18n 插件: npm install vue-i18n 创建语言资源文件(如 en.json 和 zh.json):…