工作中需要用到一個跑馬燈,網(wǎng)上找了一下,各種妖魔做法都有,明明很簡單的東西,卻要使用拼接字符串、使用計時器、還有各種文案復(fù)制什么的,更有甚者各種id,還沒從jq中走出來的樣子,思路上讓我看了略感憂傷,而且測試了一番還有bug,所以還是自己動手寫一個,其實用css3來寫思路清晰,代碼量少

跑馬燈效果圖
<template>
<section class="marquee-wrap">
<div class="marquee" ref="marquee" :style="{'animationDuration': duration}">
<span class="text-item" v-for="(item, index) of data" :key="index">{{item}}</span>
<span class="text-item" v-for="(item, index) of data" :key="`copy-${index}`">{{item}}</span>
</div>
</section>
</template>
<script>
export default {
name: 'marquee',
props: {
/* 跑馬燈數(shù)據(jù) */
data: {
type: Array,
default: () => []
},
/* 跑馬燈速度,數(shù)值越大速度越快 */
speed: {
type: Number,
default: 50
}
},
data () {
return {
duration: 0
};
},
mounted () {
/* 跑馬燈速度,使用跑馬燈內(nèi)容寬度 除以 速度 得到完整跑完一半內(nèi)容的時間 */
this.duration = ~~this.$refs.marquee.getBoundingClientRect().width / this.speed +'s';
}
};
</script>
<style lang="less" scoped>
// 自行使用 px2rem,這部分不講述
.marquee-wrap {
position: relative;
overflow: hidden;
&:after {
content: '0';
opacity: 0;
}
}
.marquee {
position: absolute;
font-size: 0;
white-space: nowrap;
animation-name: marquee;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
.text-item {
margin-right: 24px;
font-size: 24px;
/* 解決Font Boosting */
-webkit-text-size-adjust: none;
// max-height: 999px; //如果上面的依然未解決問題就加上這句吧
}
@keyframes marquee {
to { transform: translateX(-50%);}
}
</style>
這里只對跑馬燈效果進行封裝,文字顏色,外邊框,喇叭等等都由外部定義,比如以上效果圖,這樣做的好處是方便重新定義跑馬燈樣式,本人不喜歡對組件進行各種默認(rèn)定義,否則更改起來各種deep特別憂傷
<div class="marquee">
<marquee :data="options.marquee"></marquee>
</div>
<style lang="less" scoped>
// 自行使用 px2rem,這部分不講述
.marquee {
width: 544px;
padding-left: 100p;
padding-right: 30px;
line-height: 50px;
margin: 0 auto 28px;
color: #fff;
box-sizing: border-box;
border: 1px solid #f2b0ab;
border-radius: 26px;
background: url(../img/sound.png) no-repeat 42px center / 35px 35px;
}
</style>
這里說一下為什么要對marquee-wrap使用為了添加個0,因為absolute后失去了高度,用偽類補一個看不見的文字0來重新?lián)伍_可視高度。對于marquee使用absolute有兩個原因:一是對于css3動畫,我的習(xí)慣都會新建圖層;二是我需要獲取到所有文案撐開出來的寬度,使用absolute后可以讓該節(jié)點寬度自行撐出來,直接獲取即可。