Marquee.vue 1.87 KB
<template>
  <div
    class="marquee-box"
    ref="marqueeBox"
  >
    <span
      class="marquee"
      ref="marqueeText"
      :style="[{'transition': `all ${move ? speed : 0}s linear`},{'left':target}]"
    >{{text}}</span>
  </div>
</template>

<script type='text/ecmascript-6'>
export default {
  name: 'Marquee',
  props: {
    text: String,
    direction: {
      type: Number,
      default: 5000
    },
    delay: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      move: false,
      valueWidth: 0,
      target: 0,
      boxWidth: 0,
      speed: 0
    }
  },
  mounted () {
    setTimeout(() => {
      let { marqueeBox, marqueeText } = this.$refs
      let boxWidth = marqueeBox.offsetWidth,
        valueWidth = marqueeText.offsetWidth
      this.valueWidth = valueWidth
      this.boxWidth = boxWidth
      if (boxWidth - 20 <= valueWidth) this.run(valueWidth)
    }, this.delay)
  },
  methods: {
    run () {
      let { valueWidth, direction } = this
      this.target = `-${valueWidth}px`
      this.move = true
      this.speed = direction / 1000
      setTimeout(() => {
        this.again()
      }, direction)
    },
    again () {
      let { boxWidth, valueWidth, direction } = this
      this.move = false
      this.target = `${boxWidth}px`
      setTimeout(() => {
        this.speed = direction * (boxWidth / valueWidth).toFixed(2) / 1000
        this.move = true
        this.reset()
      }, 500)
    },
    reset () {
      let awaitTime = (this.speed + 2) * 1000
      this.target = 0
      setTimeout(() => {
        this.run()
      }, awaitTime)
    }
  }
}
</script>

<style scoped lang='scss'>
.marquee-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  .marquee {
    position: absolute;
    white-space: nowrap;
    display: flex;
    align-items: center;
  }
  .move {
    transform: translateX(-100%);
  }
}
</style>