vue3的一个横向文字无限滚动小组件

235 阅读1分钟

随手写了个vue3的组件,功能是超出父元素,内容文字会滚动,记录一下

通用组件:

<template>
  <div class="scroll-box" >
    <div ref="scrollContRef" :class="['scroll-content',{scrollling:scrollStart}]"
    :style="{
      animationDuration: animation.duration+'s'
    }"
    >
      <span v-html="showText"></span>
    </div>
  </div>
</template>

<script setup name="zeroTextScroll">
//使用此插件时,需要1.设置父元素宽度(获取固定的可视区域宽度,不跟随内容)2.父元素设置超出隐藏
const props = defineProps({
  text: {
    type: String,
    default: ''
  },
  //速度越大滚动越快
  speed: {
    type: Number,
    default: 50
  }
})

const showText = ref('')
const scrollContRef = ref(null)
const scrollStart = ref(false)

const animation = reactive({
  duration: 0
})

//初始化文字
const initText = ()=>{
  scrollStart.value = false
  showText.value = props.text
  nextTick(()=>{
    textScroll()
  })
}

//判断是否滚动
const textScroll = ()=>{
  const viewW = scrollContRef.value.parentElement.offsetWidth
  const textW = scrollContRef.value.offsetWidth
  let spaces = "&nbsp;".repeat(8);
  if ( textW > viewW ){
    //速度
    animation.duration = textW / props.speed *2
    //复制文字,实现无限无限滚动
    showText.value =props.text + spaces + props.text+spaces
    //开始滚动
    scrollStart.value = true
  }

}

onMounted(()=>{
  setTimeout(() => {
    initText()
  }, 0);
})
watch(()=>props.text, newVal=>{
  initText()
})

</script>

<style lang="scss" scoped>
.scroll-box{
  width: 100%;
  .scroll-content{
    width: fit-content;
  }
}
.scrollling{
  animation: scrlltext 10s linear infinite;
}

@keyframes scrlltext {
  0%{
    transform: translateX(0%);
  }
  100%{
    transform: translateX(-50%);
  }
}

</style>

使用:

      <div class="device-info">
        <ul class="flex-col">
          <li class="flex"><p>设备位置:</p> <span>{{datas.info.position}}</span> </li>
          <li class="flex"><p>设备名称:</p> <div class="info-val"><zero-text-scroll :text="datas.info.name"></zero-text-scroll></div></li>
          <li class="flex"><p>运行状态:</p> <span :style="{color:showCurColor(datas.info.status)}">{{datas.info.status}}</span></li>
          <li class="flex"><p>当前状态:</p> <span :style="{color:showCurColor(datas.info.currentStatus)}">{{datas.info.currentStatus}}</span></li>
        </ul>
      </div>