js实现列表自动滚动循环播放
1.实现效果图
鼠标移入,暂停滚动; 鼠标移出,继续滚动;
2.原理
- 要实现无缝衔接,在原有ul后面还要有一个一样内容的ul;
- 最外层div为可视区域,设overflow:hidden;
- 2个ul的高度 > 外层可视div高度,才能滚动;
3.实现代码
html:
<!-- vue -->
<div id="review_box" @mouseenter="rollStop()" @mouseleave="rollStart(60)">
<ul id="comment1">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<ul id="comment2"></ul>
</div>
css:
div {
height: 100px; /* 必须 */
overflow: hidden;/* 必须 */
}
js:
//vue data
data (){
return {
timer: null,
}
},
mounted() {
this.roll(60);
},
beforeDestroy() {
if (this.timer) clearInterval(this.timer);
},
//vue methods
roll(t) {
var ul1 = document.getElementById("comment1");
var ul2 = document.getElementById("comment2");
var ulbox = document.getElementById("review_box");
ul2.innerHTML = ul1.innerHTML;
ulbox.scrollTop = 0;
this.rollStart(t);
},
rollStart(t) {
var ul1 = document.getElementById("comment1");
var ul2 = document.getElementById("comment2");
var ulbox = document.getElementById("review_box");
this.rollStop();
this.timer = setInterval(()=>{
// 当滚动高度大于列表内容高度时恢复为0
if (ulbox.scrollTop >= ul1.scrollHeight) {
ulbox.scrollTop = 0;
} else {
ulbox.scrollTop++;
}
}, t);
},
rollStop(){
clearInterval(this.timer);
},