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>
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值