vue 实现多条文本数据在一行显示 自动循环滚动 第一条数据 连接 第二条数据 不要定时切换

<template>
  <div class="scroll-text">
    <p class="text-inner">{
   
   { scrollText }}</p>
  </div>
</template>
export default {
  data() {
    return {
      textList: ["文本1", "文本2", "文本3"], // 后台传递的文本数据
      currentIndex: 0, // 当前展示的文本索引
    };
  },
  computed: {
    //返回当前文本与下一个文本的组合。
    scrollText() {
      /* 
      将从 newsWordage 数组中获取当前索引 (currentIndex) 对应的文本,
      并将其赋值给 currentText 变量。如果获取到的值为 undefined 或 null,则将空字符串赋值给 currentText。
      */
      const currentText = this.newsWordage[this.currentIndex] || ''
       /* 
      计算了下一个索引的值(nextIndex),使用了取模运算符 % 来确保索引值在 newsWordage 数组的有效范围内循环。
      如果当前索引是数组的最后一个元素,则下一个索引是数组的第一个元素。
      */
      const nextIndex = (this.currentIndex + 1) % this.newsWordage.length
      // 把下一个文本赋值给nextText
      const nextText = this.newsWordage[nextIndex] || ''
      // 拼接上下两个文本
      return `${currentText} ${nextText}`
    },
  },
}
.scroll-text {
  width: 100%;
  height: 30px; /* 根据实际需求调整高度 */
  overflow: hidden;
}

.text-inner {
  animation: scroll 10s linear infinite; /* 根据实际需求调整滚动速度和持续时间 */
  white-space: nowrap;
  padding-top: 5px; /* 根据实际需求调整内边距 */
}

// 滚动的方向
@keyframes scroll {
  from { transform: translateX(0); }
  to { transform: translateX(-100%); }
}

在上述代码中,我们将scrollText计算属性用于生成当前要显示的文本,将当前文本和下一条文本连接起来,并利用CSS动画实现文字滚动效果。通过在scroll-keyframes中指定 transform: translateX(-100%);来控制滚动的方向和距离。

使用这种方法,文本会不断滚动,第二条数据接续在第一条数据的后面形成循环滚动效果。

猜你喜欢

转载自blog.csdn.net/weixin_53322542/article/details/134403789
今日推荐