這篇文章主要介紹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: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如何實現跑馬燈樣式文字橫向滾動”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。