vue中实现文字跑马灯

如果对你有帮助可以点个赞,有时间的话也可以来个评论。

使用translateX()来实现

<template>
  <div class="my-outbox" ref="wrap">
    <div class="my-inbox" ref="content">
      <div class="my-list">
        {
   
   { text }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      wrapWidth: 0,
      contentWidth: 0,
      text:'无缝滚动无缝滚动无缝滚动无缝滚动无缝滚动无缝滚动无缝滚动'
    };
  },
  created() {},
  mounted() {
    this.start();
  },
  methods: {
    start() {
      const { wrap, content } = this.$refs;
      this.wrapWidth = wrap.getBoundingClientRect().width;
      this.contentWidth = content.getBoundingClientRect().width;
      this.animateFn();
    },
    animateFn() {
      const { content } = this.$refs;
      let distance = this.wrapWidth;
      content.style.transform = "translateX(" + distance + "px)"; //初始值
      let that = this
      setInterval(function() {
        distance = distance - 1;
        if (-distance >= that.contentWidth) {
          distance = that.wrapWidth;
        }
        content.style.transform = "translateX(" + distance + "px)";
      }, 30); 
      //控制速度
    }
  },
  // 更新的时候运动
  updated: function() {
    this.animateFn();
  }
};
</script>

<style lang="less" scoped>
.my-outbox {
  color:#333;
  overflow: hidden;
  width:300px;
  height: 35px;
  position: relative;
  .my-inbox {
    white-space: nowrap;
    position: absolute;
    font-size: 0;
    .my-list {
      margin-right: 25px;
      display: inline-block;
      font-size: 13px;
      height: 35px;
      line-height: 35px;
    }
  }
}
</style>

猜你喜欢

转载自blog.csdn.net/tq1711/article/details/108968605
今日推荐