基于Vue的文字跑马灯组件(npm 组件包)

2020-06-16 05:38:56易采站长站整理

3.3 Marquee组件

思路:标签里的文字所占的宽度超过外面的div宽度时,增加一个内容相同的标签。这里span标签设置为display: inline-block;,可以计算其宽度,把span标签外面的父元素设置为font-size: 0;display: inline-block;,父级元素的宽度即为两者宽度之和,也就是一个span标签宽度的两倍,然后将其父级元素通过CSS3动画设置:


@keyframes marquee {
0% { transform: translateX(0); }
100% { transform: translateX(-50%);}
}

即可完美实现跑马灯效果。

具体代码:


<template>
<div class="marquee-box">
<div class="marquee-content" ref="out">
<p :class="run?speed:''">
<span class="text1" ref="in" >{{content}}</span>
<span class="text2" v-if="showtwo||run">{{content}}</span>
</p>
</div>
</div>
</template>

js:


<script>
export default {
name: 'VueMarquee',
data (){
return{
run: false,
pWidth: '',
}
},
props: {
content: {
default: "暂无内容",
type: String
},
speed: {
default: 'middle',
type: String
},
showtwo: {
default: true
}
},
mounted (){
// let out = document.getElementById(this.pid.out).clientWidth;
// let _in = document.getElementById(this.pid.in).clientWidth;
var _this = this;
this.$nextTick(()=>{
let out = _this.$refs.out.clientWidth;
let _in = _this.$refs.in.clientWidth;
_this.run=_in>out?true:false;
});
}
}
</script>

css:


<style>
.marquee-box {
height: 50px;
line-height: 50px;
color: #000;
font-size: 24px;
background-size: 24px 24px;
}
.marquee-content{
overflow: hidden;
width:100%
}
.marquee-content p{
display: inline-block;
white-space: nowrap;
margin: 0;
font-size: 0;
}
.marquee-content span{
display: inline-block;
white-space: nowrap;
padding-right: 40px;
font-size: 24px;
}
.quick{
-webkit-animation: marquee 5s linear infinite;
animation: marquee 5s linear infinite;
}
.middle{
-webkit-animation: marquee 8s linear infinite;
animation: marquee 8s linear infinite;
}
.slow{
-webkit-animation: marquee 25s linear infinite;
animation: marquee 25s linear infinite;
}
@-webkit-keyframes marquee {
0% { -webkit-transform: translate3d(0,0,0); }
100% { -webkit-transform: translate3d(-50%,0,0); }
}
@keyframes marquee {
0% { transform: translateX(0); }