当前位置:首页 > 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 中实现循环 Vue 提供了 v-for 指令用于实现循环渲染列表数据。v-for 可以遍历数组、对象或数字范围,生成动态的 DOM 元素。 遍历数组 使用 v-for 遍历数组时,语法为…

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

vue实现详情

vue实现详情

Vue 实现详情页的常见方法 使用动态路由 在 Vue Router 中配置动态路由参数,通过 $route.params 获取详情 ID。示例路由配置: { path: '/detail/:i…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── Ka…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装 scre…

vue实现必填

vue实现必填

Vue 实现表单必填验证的方法 在Vue中实现表单必填验证可以通过多种方式完成,以下是几种常见的方法: 使用HTML5原生属性 最简单的必填验证可以通过HTML5的required属性实现: &l…