
鼠標放上去可暫停,當前實現版本是字數長度要超過外層div才會滾動
父界面:
<template>
<div>
<el-card style="width: 97%;margin-top: 10px;margin-left: 22px;" >
<marque style="width: 100%;height: 30px;color: red;font-size: 18px;margin-left: 10px;" :lists="['這是一個很長很長很長的跑馬燈']" ></marque>
</el-card>
</div>
</template>
<script>
import marque from '@/components/marque'
export default {
components: {
marque
}
}
</script
子界面,(跑馬燈組件)
1 <template> 2 <div class="marquee-wrap" @mouseover='stopInter' @mouseleave='startInter'> 3 <!-- 滾動內容 --> 4 <div class="scroll" style=" text-shadow:#ffc773 0 1px 8px;color: #ed5736;"> 5 <p class="marquee">{{text}}</p> 6 <!-- 文字副本 --> 7 <p class="copy"></p> 8 </div> 9 <!-- 為了計算總文本寬度,通過css在頁面中隱藏 --> 10 <p class="getWidth">{{text}}</p> 11 </div> 12 </template> 13 14 <script> 15 export default { 16 props: ['lists'], // 父組件傳過來的數組 17 data () { 18 return { 19 timer: null, 20 text: '', 21 intervalStop: false 22 } 23 }, 24 created () { 25 // 進入頁面等一秒才開始滑動 26 let timer = setTimeout(() => { 27 this.move() 28 clearTimeout(timer) 29 }, 1000) 30 }, 31 // 把父組件傳入的arr轉化成字符串, 本次是傳入一個,在此處重復了三次來獲取足夠的長度 32 mounted () { 33 for (let item of this.lists) { 34 this.text += ' ' + item + ` ` + item + ` `+ item 35 } 36 }, 37 methods: { 38 stopInter() { 39 this.intervalStop = true; 40 }, 41 startInter() { 42 this.intervalStop = false; 43 }, 44 move () { 45 let maxWidth = document.querySelector('.marquee-wrap').clientWidth 46 // 獲取文字text 的計算后寬度 (由於overflow的存在,直接獲取不到,需要獨立的node計算) 47 let width = document.querySelector('.getWidth').scrollWidth 48 // 如果文本內容的寬度小於頁面寬度,則表示文字小於等於一行,則不需要滾動 49 if (width <= maxWidth) return 50 let scroll = document.querySelector('.scroll') 51 let copy = document.querySelector('.copy') 52 copy.innerText = this.text // 文字副本填充 53 let distance = 0 // 位移距離 54 // 設置位移 55 this.timer = setInterval(() => { 56 if (!this.intervalStop) { 57 distance -= 1 58 // 如果位移超過文字寬度,則回到起點 59 if (-distance >= width) { 60 distance = 10 // 距離必須與marquee的margin寬度相同 61 } 62 scroll.style.transform = 'translateX(' + distance + 'px)' 63 } 64 }, 20) 65 } 66 }, 67 beforeDestroy () { 68 // 清除計時器 69 clearInterval(this.timer) 70 } 71 } 72 </script> 73 <style scoped lang='less'> 74 .marquee-wrap { 75 width: 100%; 76 overflow: hidden; 77 position: relative; 78 .scroll { 79 display: flex; 80 p{ 81 word-break:keep-all; // 不換行 82 white-space:nowrap; 83 /* 設置前后間隔 */ 84 &.marquee { 85 margin-right: 32px; 86 } 87 } 88 } 89 /* 僅為了獲取寬度,故隱藏掉 */ 90 .getWidth { 91 word-break:keep-all; // 不換行 92 white-space:nowrap; 93 position: absolute; 94 opacity: 0; 95 top: 0; 96 } 97 } 98 </style>
參考:https://blog.csdn.net/weixin_43931876/article/details/90046945
