通知公告上下循环滚动播放:
let noticeMsg = new Vue({
el: '#noticeMsg',
data: {
infoList: [],//通知公告列表
timer: "",//播放定时器
speeds: 10, //滚动的速度,单位ms
currentTop:0,//当前滚动上偏移量
pauseDuring:3000//通知公告的停顿时间
},
methods: {
// 初始化通知公告
initNotice() {
setTimeout(() => {
this.infoList = result.data;
// 只有一条以下的公共就停掉通知公告的滚动
if(this.infoList.length <= 1){
clearInterval(this.timer);
}
}, 3000);
},
// 公告滚动,只有一条的时候应该不需要滚动
noticeRun(){
let noticeList = this.$refs['noticeList'];
if(!noticeList)return;
this.currentTop--;
noticeList.style.top = this.currentTop + "px";
//当页面滚动最后一个时,把第一个复制push到尾部
if (this.currentTop == (this.infoList.length - 1) * -42) {
let div = document.createElement("div");
div.className ="notice";
div.innerHTML = `<span class="noticeText" v-html ="${this.infoList[0]}"></span>`;
noticeList.appendChild(div);
}
//无缝替换
if (this.currentTop == this.infoList.length * -42) {
this.currentTop = 0;
noticeList.style.top = this.currentTop + "px";
noticeList.removeChild(noticeList.lastElementChild);
}
//滚动后每个消息是否需要暂停
if (this.currentTop % 42 == 0) {
clearInterval(this.timer);
setTimeout(() => {
this.timer = setInterval(this.noticeRun, this.speeds);
}, this.pauseDuring);
}
}
},
// DOM创建以后开启定时器
mounted() {
this.timer = setInterval(this.noticeRun, this.speeds);
},
// 在销毁实例之前清除定时器
beforeDestroy() {
clearInterval(this.timer);
}
});