前言
实现多条通知拼接为一条消息播报的文章:
本篇文章需要实现,上一条播报结束后,下一条通知再播报,而不是拼接为一串通知播报。
首先我们需要一个定时器来控制当前消息的向左平移样式,然后我们需要一个偏移的变量offset,给offset一个初始值,初始值就是当前container容器的宽度,通过一个固定的速度speed,作为定时器的间隔时间,每个间隔时间,向左平移step的距离。
然后判断当前偏移位置是否全部播报完成,如果播报完成,则重置我们的偏移变量offset。
一、实现步骤
1.HTML代码
代码如下(示例):
<div class="container" id="notification-container">
<div class="notification" id="notification">
{{ notificationtext }}
</div>
</div>
2.JS代码
代码如下(示例):
data() {
return {
noticeList: [],
notificationtext: "",
noticeTimer: null,
itemWidth: 0,
offset: 0,
step: 3,
speed: 20,
};
},
methods: {
setNotificationMove() {
// 清除定时器
clearInterval(this.noticeTimer);
const notificationContainer = document.getElementById(
"notification-container"
);
const notificationWidth = notificationContainer.offsetWidth;
let index = 0;
// 播报内容赋值
this.notificationtext = this.noticeList[index];
const notification = document.getElementById("notification");
this.offset = notificationWidth;
// 初始化x轴平移距离
notification.style.transform = `translateX(${this.offset}px)`;
// 当前通知的宽度
this.itemWidth = this.notificationtext.length * 20;
this.noticeTimer = setInterval(() => {
this.offset -= this.step;
if (this.offset < -this.itemWidth) {
this.offset = notificationWidth;
if (index >= this.noticeList.length - 1) {
index = 0;
} else {
index++;
}
this.notificationtext = this.noticeList[index];
this.itemWidth = this.notificationtext.length * 20;
}
notification.style.transform = `translateX(${this.offset}px)`;
}, this.speed);
},
},
mounted(){
this.setNotificationMove();
},
beforeDestroy() {
clearInterval(this.noticeTimer); // 清除定时器
},
优化
如果需要更新通知列表,但是当前仍有消息在进行滚动,我们可以优化显示效果,等当前滚动结束,再更新通知列表。实现方法是:获取当前偏移位置,将剩下的滚动时间计算出来,添加一个setTimeout,等当前通知滚动完成,再重新调用setNotificationMove方法。
代码如下(示例):
delayNoticeMove(){
const notification = document.getElementById("notification");
let currentOffset = notification.style.transform;
if (currentOffset) {
currentOffset = currentOffset.split("(")[1];
currentOffset = currentOffset.substring(0, currentOffset.indexOf("px"));
let duration = ((Number(currentOffset) + this.itemWidth) / this.step) * this.speed;
// 判断当前还有多久滚动完毕 添加一个setTimeout等待滚动结束后重新计时
setTimeout(() => {
this.setNotificationMove();
}, duration);
} else {
this.setNotificationMove();
}
}