vue 文字滚动

482 阅读1分钟
<template>
  <div class="wrap" ref="wrap" @mouseover="mouseover" @mouseleave="mouseleave" :style="active">
    <div ref="box" class="box">
      <div ref="marquee" class="marquee">{{text}}</div>
      <!--<div ref="copy" class="copy"></div>-->
    </div>
    <div ref="node" class="node">{{text}}</div>
  </div>
</template>
<script>
  export default {
    name: 'Marquee',
    props: ['lists'],
    data () {
      return {
        text: '',
        timer: null,
        active: '',
        distance: 0
      }
    },
    methods: {
      move () {
        if (this.$refs.node.getBoundingClientRect().width > this.$refs.wrap.getBoundingClientRect().width - 50) {
          // 获取文字text 的计算后宽度  (由于overflow的存在,直接获取不到,需要独立的node计算)
          let width = this.$refs.node.getBoundingClientRect().width
          console.log(width);
          // this.$refs.copy.innerText = this.text // 文字副本填充
          // 设置位移
          this.timer = setInterval(() => {
            this.distance = this.distance - 1
            // 如果位移超过文字宽度,则回到起点
            if (-this.distance >= width) {
              this.distance = 16
            }
            this.$refs.box.style.transform = 'translateX(' + this.distance + 'px)'
          }, 30)
        }
      },
      mouseover () {
        clearInterval(this.timer)
      },
      mouseleave () {
        this.move()
      },
    },
    mounted: function () {
      this.text = this.lists
    },
    // 更新的时候运动
    updated: function () {
      this.$nextTick(() => {
        this.move()
      })
    }
  }
</script>
<style scoped lang="scss">

  .wrap {
    overflow: hidden;
  }

  .box {
    width: 80000%;
  }

  .box div {
    float: left;
  }

  .marquee {
    margin: 0 16px 0 0;
  }

  .node {
    position: absolute;
    z-index: -999;
    top: -999999px;
  }
</style>