1. 程式人生 > 程式設計 >Vue實現跑馬燈樣式文字橫向滾動

Vue實現跑馬燈樣式文字橫向滾動

本文例項為大家分享了實現跑馬燈樣式文字橫向滾動的具體程式碼,供大家參考,具體內容如下

需求:

在Vue專案的頂部,來實現文字左右滾動

步驟:

1、可以自己封裝一個元件,也可以自己寫,也可以複製以下程式碼
2、封裝完成以後要在所需的元件中引入,註冊,並使用

程式碼:

封裝一個專門用來實現跑馬燈效果的元件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:n
owrap; position: absolute; opacity: 0; top: 0; } </sthttp://www.cppcns.comyle>

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

// 引入跑馬燈元件
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實現跑馬燈樣式文字橫向滾動

Vue實現跑馬燈樣式文字橫向滾動

Vue實現跑馬燈樣式文字橫向滾動

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。