- marquee標(biāo)簽已經(jīng)廢棄了壶笼,只能手動(dòng)實(shí)現(xiàn)文字走馬燈樣式
- 基于vue組件開發(fā)
- 感謝@藝術(shù)青年陳國(guó)良提醒虐沥,用
ref
獲取元素,可以在頁面中多處應(yīng)用
<template>
<div class="wrap">
<div ref="box" class="box">
<div ref="marquee" class="marquee">{{text}}</div>
<div ref="copy" class="copy"></div>
</div>
<div ref="node" class="node">{{text}}</div>
</div>
</template>
<script>
export default {
name : 'Marquee',
props: ['lists'], // 父組件傳入數(shù)據(jù), 數(shù)組形式 [ "連雨不知春去","一晴方覺夏深"]
data () {
return {
text: '' // 數(shù)組文字轉(zhuǎn)化后的字符串
}
},
methods: {
move () {
// 獲取文字text 的計(jì)算后寬度 (由于overflow的存在脏榆,直接獲取不到猖毫,需要獨(dú)立的node計(jì)算)
let width = this.$refs.node.getBoundingClientRect().width
this.$refs.copy.innerText = this.text // 文字副本填充
let distance = 0 // 位移距離
// 設(shè)置位移
setInterval(() => {
distance = distance - 1
// 如果位移超過文字寬度,則回到起點(diǎn)
if (-distance >= width) {
distance = 16
}
this.$refs.box.style.transform = 'translateX(' + distance + 'px)'
}, 20)
}
},
// 把父組件傳入的arr轉(zhuǎn)化成字符串
mounted: function () {
for (let i = 0; i < this.lists.length; i++) {
this.text += ' ' + this.lists[i]
}
},
// 更新的時(shí)候運(yùn)動(dòng)
updated: function () {
this.move()
}
}
</script>
<style scoped>
.wrap {
overflow: hidden;
}
.box {
width: 80000%;
}
.box div {
float: left;
}
.marquee {
margin: 0 16px 0 0;
}
.node {
position: absolute;
z-index: -999;
top: -999999px;
}
</style>
父組件引入 import myMarquee from './my-marquee
使用并傳參: <my-marquee :lists="lists"></my-marquee>
參數(shù):
data (){
return {
lists: [
'連雨不知春去',
'一晴方覺夏深'
]
}
}