vue实现无缝跑马灯

结合代码说说实现原理吧。
HTML部分

<!-- 父盒子固定宽度,overflow: hidden用于滚动 -->
 <div class="competition-dynamics-warp-box" ref="wrapper">
<!--滚动区域的盒子,里面放需要滚动的内容,注意再复制一份用于实现无缝对接 -->
    <div
      class="marquee-box"
      ref="marquee"
      @mouseover="mouseover"
      @mouseout="mouseout"
    >
      <!-- 滚动内容 -->
      <div class="img-box" v-for="(item, index) in dataList" :key="index">
        <img class="img" src="../../../assets/images/home10.png" />
        <div class="title">金融大数据处理职业课程{{ index }}</div>
      </div>
       <!-- 复制一份滚动内容,用于实现无缝对接-->
      <div class="img-box" v-for="(item, index) in dataList" :key="index + 100">
        <img class="img" src="../../../assets/images/home10.png" />
        <div class="title">金融大数据处理职业课程{{ index }}</div>
      </div>
    </div>
  </div>

js部分代码

export default {
  name: "competition-dynamics",
  data() {
    return {
      dataList: [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
      timer: null,
      box: "",
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    //元素超过4个之后才开始新建定时器实现滚动
    init() {
      if (this.dataList.length > 4) {
        this.box = this.$refs.wrapper;
        this.timer = setInterval(() => {
          this.move();
        }, 10);
      }
    },
    // 跑马灯工作
    move() {
      let curLeft = this.box.scrollLeft;
      //父盒子总宽度除以2 (20是我这边盒子之间的右边距)
      let scrollWidth = this.$refs.marquee.scrollWidth / 2 + 20;
      this.box.scrollLeft = curLeft + 1;
      if (curLeft > scrollWidth) {
        this.box.scrollLeft = 0;
      }
    },
    //鼠标悬停
    mouseover() {
      clearInterval(this.timer);
      this.timer = null;
    },
    //鼠标离开,继续滚动
    mouseout() {
      this.init();
    },
  },
  //销毁定时器
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  },
};

css部分代码

<style lang="scss" scoped>
.competition-dynamics-warp-box {
  width: 1200px;
  height: 210px;
  overflow: hidden;
  position: relative;
  .marquee-box {
    display: flex;
    .img-box {
      margin-right: 40px;
      .img {
        width: 270px;
        height: 160px;
      }
      .title {
        width: 270px;
        height: 50px;
        background: #ffffff;
        border-radius: 0px 0px 6px 6px;
        text-align: center;
        line-height: 50px;
        font-size: 16px;
        font-family: Noto Sans S Chinese;
        font-weight: 400;
        color: #333333;
        margin-top: -2px;
      }
    }
  }
}
</style>

从上面代码不难看出相对于原生的js,使用vue实现无缝连接的跑马灯要相对容易的多。首先是使用ref拿到父盒子的scrollLeft,再和其中的一个滚动盒子的内容宽度进行对比。如果父盒子的scrollLeft超过一个滚动盒子的内容宽度就置0从头开始,这样就可以实现无缝对接了。其次,如果需要鼠标悬停的也非常简单,mouseover()方法清除定时器即可,鼠标离开重新开始,mouseout()方法内重新调用init()方法即可。真的是省时省力太便捷了。
ps:页面销毁前记得清除定时器呀,beforeDestroy()中调用清除就行啦。内容较简单先这样吧,本篇over~下次见!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容