vue项目中javascript实现通知公告的上下循环滚动播放

通知公告上下循环滚动播放:

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);
	}
});
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值