Vue3 简单的实现文字无限滚动_滚动文字

 
<template>
  <div class="test-box">
    <div
      class="test-block"
      :style="{ transform: `translateY(-${topPx}px)`, transition: topPx === 0 ? `none 0s` : `all .5s ease-in-out` }"
      v-for="(item, index) in testList"
      :key="index"
    >
      {{ item }}
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  let topPx = ref(0);
  let testList = ref(['777777', '111111', '222222', '333333', '444444', '555555', '666666', '777777']);
 
  onMounted(() => {
    topPxChange();
  });
 
  function topPxChange() {
    topPx.value += 50;
 
    if (topPx.value >= testList.value.length * 50) {
      topPx.value %= testList.value.length * 50; // 使用取模运算确保值在有效范围内循环
    }
 
    setTimeout(
      () => {
        topPxChange();
      },
      topPx.value === 0 ? 0 : 1500
    );
  }
</script>
 
<style lang="less" scoped>
  .test-box {
    width: 200px;
    height: 50px;
    background: #f0f0f0;
    overflow: hidden;
 
    .test-block {
      width: 100%;
      height: 100%;
      line-height: 50px;
      transition: all 0.5s ease-in-out;
    }
  }
</style>