setInterval -- 间隔执行函数;element.scrollTop -- 元素滚动条距头部的距离;
因为执行代码需要时间,所以最终动态时间会比设置的要慢
var slide = new Slide({ id:'grid-body',//元素ID onceHeight:43,//每行高度 onceTime:500,//滑动一次用时毫秒 wait:1500//滑动后停顿毫秒 }); slide.start();
function Slide(options){ this.element = document.getElementById(options.id); //元素 this.onceHeight = options.onceHeight || 40;//滚动距离 this.onceTime = options.onceTime || 200;//滚动一次需要的时间 this.wait = options.wait || 1000;//等待时长(滚动一次后多久滚动下一次 单位:毫秒) this.frame = 1;//帧数 this.frequency = this.onceTime / (this.onceHeight / this.frame); this.waitPoint = this.onceTime / this.frequency; this.coming = this.waitPoint + this.wait / this.frequency; this.prevFrame = this.element.scrollHeight / (this.onceTime / this.frequency); this.start = function(){ let _this=this, j=this.waitPoint, isPrev=false; //用户滚动鼠标时暂停滚动 _this.element.onmousewheel = function(){ //准备停顿 j = _this.waitPoint; } //开始滚动 setInterval(function(){ if(isPrev){//滚回顶部 _this.element.scrollTop -= _this.prevFrame; //判断是否滚动到顶部; if(_this.element.scrollTop <= 0){ //开始往下滑动 isPrev = false; //准备等待 j = _this.waitPoint; } }else{ j++; //等待结束 if(j >= _this.coming){ //准备滑动 j = 0; //判断是否滚动到底部; if(_this.element.scrollTop + _this.element.clientHeight >= _this.element.scrollHeight){ //开始往上滑动 isPrev = true;return; } } //等待…… if(j >= _this.waitPoint)return; //设置滚动条到顶部距离 _this.element.scrollTop += _this.frame; } },this.frequency); } }