溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue如何實現(xiàn)跑馬燈樣式文字橫向滾動

發(fā)布時間:2021-11-23 11:05:22 來源:億速云 閱讀:757 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹Vue如何實現(xiàn)跑馬燈樣式文字橫向滾動,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

需求:

在Vue項目的頂部,來實現(xiàn)文字左右滾動

步驟:

1、可以自己封裝一個組件,也可以自己寫,也可以復(fù)制以下代碼
2、封裝完成以后要在所需的組件中引入,注冊,并使用

代碼:

封裝一個專門用來實現(xiàn)跑馬燈效果的組件marquee組件

<template>
<!-- 跑馬燈組件 -->
  <div class="marquee-wrap" ref="marquee-wrap">
    <div class="scroll" ref="scroll">
      <p class="marquee">{{text}}</p>
      <p class="copy" ref="copy"></p>
    </div>
    <p class="getWidth" ref="getWidth">{{text}}</p>
  </div>
</template>

<script>
export default {
  name: 'marquee',
  props: ['val'],
  data () {
    return {
      timer: null,
      text: ''
    }
  },
  created () {
    let timer = setTimeout(() => {
      this.move()
      clearTimeout(timer)
    }, 1000)
  },
  mounted () {
    for (let item of this.val) {
    this.text += item
    }
  },
  methods: {
    move () {
    let maxWidth = this.$refs['marquee-wrap'].clientWidth
    let width = this.$refs['getWidth'].scrollWidth
      if (width <= maxWidth) return
    let scroll = this.$refs['scroll']
    let copy = this.$refs['copy']
      copy.innerText = this.text
      let distance = 0 
      this.timer = setInterval(() => {
        distance -= 1
        if (-distance >= width) {
          distance = 16
        }
        scroll.style.transform = 'translateX(' + distance + 'px)'
      }, 20)
    }
  },
  beforeDestroy () {
    clearInterval(this.timer)
  }
}
</script>

<style scoped>
  .marquee-wrap {
    width: 100%;
    overflow: hidden;
    position: relative;
  }
  .marquee{
    margin-right: 0.16rem;
  }
  p {
    word-break:keep-all;
    white-space: nowrap;
    font-size: 0.28rem;
  }
  .scroll {
    display: flex;
  }
  .getWidth {
    word-break:keep-all;
    white-space:nowrap;
    position: absolute;
    opacity: 0;
    top: 0;
  }
</style>

在哪個組件中使用,就引入

// 引入跑馬燈組件
import  marquee  from "@/components/marquee/marquee.vue";

引用并注冊

export default {
  components: {
  // 注冊跑馬燈組件
    marquee,
  },
 }

注冊完成以后接下來就是Html樣式了,在template模板中使用這個組件

<Marquee class="realData">
          <ul class="fa-scroll-cont">
            <li v-for="item in realData" :key="item.name">
              <span class="roll-text">{{ item.city }}</span>
            </li>
          </ul>
</Marquee>

接下來就是效果圖:
為了效果看的更明顯多截了幾張

Vue如何實現(xiàn)跑馬燈樣式文字橫向滾動

Vue如何實現(xiàn)跑馬燈樣式文字橫向滾動

Vue如何實現(xiàn)跑馬燈樣式文字橫向滾動

以上是“Vue如何實現(xiàn)跑馬燈樣式文字橫向滾動”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI