html:
<div class="all" id='all'>
<div class="screen">
<ul>
<li><img src="images/1.jpg" width="500" height="200" /></li>
<li><img src="images/2.jpg" width="500" height="200" /></li>
<li><img src="images/3.jpg" width="500" height="200" /></li>
<li><img src="images/4.jpg" width="500" height="200" /></li>
<li><img src="images/5.jpg" width="500" height="200" /></li>
</ul>
</div>
css:
* {
padding: 0;
margin: 0;
list-style: none;
border: 0;
}
.all {
width: 500px;
height: 200px;
padding: 7px;
border: 1px solid #ccc;
margin: 100px auto;
position: relative;
}
.screen {
width: 500px;
height: 200px;
overflow: hidden;
position: relative;
}
.screen li {
width: 500px;
height: 200px;
overflow: hidden;
float: left;
}
.screen ul {
position: absolute;
left: 0;
top: 0px;
width: 3000px;
}
js:
//非ie兼容,获取当前位置
function getStyle(obj,attr){
if(window.getCompuedStyle){
return window.getComputedStyle(obj,null)[attr];
}
return obj.currentStyle[attr];
}
//位置改变
function animate(oEle,attr,target){
clearInterval(oEle.timer);
oEle.timer=setInterval(()=>{
//当前位置
let current=parseInt(getStyle(oEle,attr));
//步长
let step=target>current?10:-10;
oEle.style[attr]=current+step+"px";
//如果目标值-当前值,不足1步时,清除定时器
if(Math.abs(target-current)<=Math(step)){
clearInterval(oEle.timer);
oEle.style[attr]=target+"px";
}
})
}
var oUl=document.querySelector("ul");
oUl.appendChild(oUl.children[0].cloneNode(true));
//自动轮播
var imgIndex=0;
function autoplay(){
imgIndex++;
if(imgIndex>5){
oUl.style.left="0px";
imgIndex=1;
}
animate(oUl,"left",-imgIndex*500);
}
var timer=setInterval(autoplay,1500);