项目开发中遇到文字跑马灯功能需求,最开始使用vue + interstart
<div class="content-carousel">
@{{ msg }}
</div>
<script>
new Vue({
data : {
msg : ['123','322']
}
mounted() {
this.move();
},
methods : {
move() {
setInterval(() => {
let start = this.msg.slice(0, 1);
let end = this.msg.slice(1);
this.msg = end + start;
}, 250)
}
}
})
</script>
此方法优点是简单,易维护。缺点是播放生硬,有顿挫感,interstart也有些耗性能
展示效果有硬伤,后来尝试css animation实现
.content-carousel {
background : linear-gradient(to right, #FF8B75, #FF2282);
top : 53%;
border-radius : 12px;
width : 75%;
height : 19px;
left : 0;
right : 0;
margin : auto;
padding : 0 10px;
overflow : hidden;
.carousel-cont {
position : absolute;
width : 200%; /* 宽度 大于容器的两倍即可 */
height : 100%;
animation : 5s move infinite linear;
p {
color : #fff;
display : inline-block;
/* 宽度 等于容器的宽度 */
width : 50%;
line-height : 19px;
text-align : center;
}
}
@-webkit-keyframes move {
/* 原理 left值的变化 移动一个容器的宽度 */
0% {
left : 0;
}
100% {
left : -200%;
}
}
}
<div class="content-carousel">
<div class="carousel-cont">
<p v-for="item in msg">
@{{ item }}
</p>
</div>
</div>
动画属性很漂亮,解决了播放顿挫感,但实际应用中发现,如果数据可变,动画属性的值跟着变化才能实现功能,但无奈动画属性无法通过js确定,只好作罢
最终确定使用 JQuery animate方法
.content-carousel {
background : linear-gradient(to right, #FF8B75, #FF2282);
top : 28rem;
border-radius : 12px;
width : 75%;
height : 19px;
line-height : 19px;
left : 0;
right : 0;
margin : auto;
padding : 0 10px;
overflow : hidden;
p {
white-space : nowrap;
position : absolute;
left : 0;
display : inline-flex;
span {
color : #fff;
margin-right : 50px;
}
}
}
<div class="content-carousel">
<p id="carousel-text">
<span v-for="item in msg"
:key="item">
@{{ item }}
</span>
</p>
</div>
<script>
new Vue({
mounted() {
this.move();
},
methods : {
move() {
let containerDom = $('.content-carousel');
let moveDom = $('#carousel-text');
moveDom.animate({left : -(moveDom.width() - containerDom.width()) + 'px'}, this.msg.length * 4000, 'linear', () => {
moveDom.css({
left : containerDom.width() + 'px'
});
this.move()
})
}
})
</script>
顿挫感和数据可变情况下的播放完整性都成功解决,希望可以帮到有相应需求的同行们