vue文字广告循环匀速滚动效果

需求:vue实现文字在div中从左到右实现循环滚动效果,鼠标移入暂停滚动,鼠标移出继续滚动,从后端拿到文本数据,不管数据长短,循环匀速播放。

实现:

  <template>
  <div class="scroll-container">
    <div
      class="scroll-text"
      :class="{ paused: isPaused }"
      :style="{ animationDuration: duration }"
      @click="toggleScroll"
      ref="scrollContainer"
    >
      {{ text }}
    </div>
  </div>
</template>

  <script>
export default {
  data () {
    return {
      text: '1233  333 444 555',
      duration: "0s",
      isPaused: false,
    };
  },
  mounted () {
    // 如果抽组件内容需要在watch中监听父组件传过来的后写以下方法:(因在父组件中data定义的是空值,会导致变快)
    // 获取内容宽度
    this.$nextTick(() => {
      const textWidth = this.$refs.scrollContainer.scrollWidth;
      let duration = textWidth / 30;
      // 设置一定速度值,避免太短或太长导致过快或过慢
      if (duration < 1.5) {
        duration = 1.5
      }// 10s for 1000px
      this.duration = duration + "s";
      console.log(textWidth, this.duration)
    })
  },
  methods: {
    toggleScroll () {
      this.isPaused = !this.isPaused;
    },
  },
};
  </script>

  <style>
.scroll-container {
  width: 200px;
  height: 1.2em;
  overflow: hidden;
  border: 1px solid #ccc;
  position: relative;
}

.scroll-text {
  position: absolute;
  top: 0;
  left: 0;
  white-space: nowrap;
  animation: scrollText 0s linear infinite;
  transition: transform 0.3s ease-out;
  cursor: pointer;
}

.scroll-text.paused {
  animation-play-state: paused;
}

.scroll-text:hover {
  animation-play-state: paused;
}

@keyframes scrollText {
  0% {
    /* 播放完成循环播放 */
    transform: translateX(300px);
  }
  100% {
    transform: translateX(-100%);
  }
}
</style>

你可能感兴趣的:(vue.js,javascript,前端)