<!-- 文字跑馬燈 --> <template> <div class="wrap"> <div ref="box" class="box"> {{text}} </div> </div> </template> <script> export default { data () { return { timer: null, text: '文本滾動', } }, methods: { startText () { if(this.timer != null) return; let width = this.getLenPx(this.text, 26) let distance = 400; // 設為0從左側開始播放 this.timer = setInterval(() => { distance = distance - 1; // 如果位移超過文字寬度,則回到起點 if (-distance >= width) { distance = 400 } this.$refs.box.style.transform = 'translateX(' + distance + 'px)'; }, 10) }, stopText () { //清除定時器 clearInterval(this.timer) //清除定時器之后,需要重新將定時器置為null this.timer = null }, // 獲取字符串占位px getLenPx(str, font_size) { var str_leng = str.replace(/[^\x00-\xff]/gi, 'aa').length; return str_leng * font_size / 2 } }, mounted () { this.startText() }, destroyed () { this.stopText() } } </script> <style lang='scss' scoped> .wrap { width: 400px; overflow: hidden; } .box { width: 8000%; overflow: hidden; } </style>
網上有好多例子,總覺得不太好,自己改了改,還算滿意,不足之處歡迎各位指出。(為了方便大家做了稍微改動)
下面是我沒改動代碼
<!-- 文字跑馬燈 --> <template> <div class="wrap"> <div ref="box" class="box"> {{element.propValue[0]}} </div> </div> </template> <script> export default { data () { return { timer: null } }, props: { element: { type: Object, }, }, methods: { startText () { if(this.timer != null) return; let width = this.getLenPx(this.element.propValue[0], this.element.style.fontSize) let distance = this.element.style.width; // 設為0從左側開始播放 this.timer = setInterval(() => { distance = distance - 1; // 如果位移超過文字寬度,則回到起點 if (-distance >= width) { distance = this.element.style.width } this.$refs.box.style.transform = 'translateX(' + distance + 'px)'; }, 10) }, stopText () { //清除定時器 clearInterval(this.timer) //清除定時器之后,需要重新將定時器置為null this.timer = null }, // 獲取字符串占位px getLenPx(str, font_size) { var str_leng = str.replace(/[^\x00-\xff]/gi, 'aa').length; return str_leng * font_size / 2 } }, mounted () { this.startText() }, destroyed () { this.stopText() } } </script> <style lang='scss' scoped> .wrap { overflow: hidden; } .box { width: 8000%; overflow: hidden; } </style>