vue文字跑马灯

vue文字跑马灯

<script setup>
import { nextTick, onBeforeUnmount, onMounted, ref } from "vue"
const props = defineProps(['lists'])
const text = ref("")
const textCopy = ref("")
const timmer = ref(null)
const maxWidth = ref(0)
const textWidth = ref(0)
const distance = ref(0)
const marquee = ref(null)
const calcute = () => {
  maxWidth.value = document.querySelector('.marquee-wrap').clientWidth
  // 获取文字text 的计算后宽度
  textWidth.value = document.querySelector('.getWidth').scrollWidth
  // 如果文本内容的宽度小于页面宽度,则表示文字小于等于一行,则不需要滚动
  distance.value = 0
  if (textWidth.value <= maxWidth.value) {
    textCopy.value = ""
    return
  }
  textCopy.value = text.value // 文字副本填充
  tMove()
}
const tMove = () => {
  distance.value -= 1
  if (-distance.value >= textWidth.value) {
    distance.value = 0 
    cancelAnimationFrame(timmer.value)
    text.value = props.lists.join(' ')
    nextTick(() => calcute())
  } else {
    timmer.value = requestAnimationFrame(tMove)
  }
  marquee.value.style.transform = 'translateX(' + distance.value + 'px)'
}
onMounted(() => {
  text.value = props.lists.join(' ')
  nextTick(() => calcute())
})
onBeforeUnmount(() => {
  cancelAnimationFrame(timmer.value)
})
</script>
<template>
  <div class="marquee-wrap">
    <!-- 滚动内容 -->
    <div class="marqueeScroll" ref="marquee">
      <p class="marquee">{{ text }}</p>
      <!-- 文字副本 -->
      <p class="marqueeCopy">{{ textCopy }}</p>
    </div>
    <!-- 为了计算总文本宽度,通过css在页面中隐藏 -->
    <p class="getWidth">{{ text }}</p>
  </div>
</template>
<style scoped>
.marquee-wrap {
  width: 100%;
  overflow: hidden;
  position: relative;
}
.marqueeScroll {
  display: flex;
}
.marqueeScroll p {
  word-break: keep-all;
  white-space: nowrap;
  text-indent: 1em;
}
.marquee {
  margin-right: 0px;
}
/* 仅为了获取宽度,故隐藏掉 */
.getWidth {
  word-break: keep-all;
  white-space: nowrap;
  position: absolute;
  opacity: 0;
  top: 0;
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值