原生JS手写无缝滚动
css
*{
margin: 0;
padding: 0;
}
.div1{
list-style: none;
margin: 100px auto;
width: 712px;
height: 108px;
background: red;
position: relative;
overflow: hidden;
}
.div1 ul{
list-style: none;
position: absolute;
left: 0;
top: 0;
}
.div1 ul li{
float: left;
width: 178px;
height: 108px;
}
html
js部分
var oUl = document.getElementsByTagName('ul')[0];
var aLi = oUl.getElementsByTagName('li');
var aBtn1 = document.querySelector('#btn1')
var aBtn2 = document.querySelector('#btn2')
var timer = null;
var a;
oUl.innerHTML=oUl.innerHTML+oUl.innerHTML;
oUl.style.width=aLi[0].offsetWidth*aLi.length+'px';
autoPlay(-5);
function autoPlay(speed){
clearInterval(timer)
timer = setInterval(function(){
if(oUl.offsetLeft <= -oUl.offsetWidth/2){
oUl.style.left=0;
}
else if(oUl.offsetLeft >=0){
oUl.style.left=-oUl.offsetWidth/2+'px';
}
oUl.style.left=oUl.offsetLeft+speed+'px';
a=speed;
},10)
}
oUl.onmouseover=function(){
clearInterval(timer);
}
oUl.onmouseout=function(){
if(a>0){
autoPlay(5);
}
else{
autoPlay(-5);
}
}
aBtn2.onclick=function(){
autoPlay(5);
}
aBtn1.onclick=function(){
autoPlay(-5);
}