利用框架移动盒子(两个参数1.元素2.目标位置)
animate(ul,-this.index*490);
function animate(ele,target) {
clearInterval(ele.timer);
var speed=target>ele.offsetLeft?10:-10;
ele.timer=setInterval(function () {
var val=target-ele.offsetLeft;
ele.style.left=ele.offsetLeft+speed+"px";
if(Math.abs(val)<Math.abs(speed)){
ele.style.left=target+"px";
clearInterval(ele.timer);
}
},1);
}
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
padding:0;
margin: 0;
}
.box{
width:490px;
height: 170px;
padding:5px;
border:1px solid #cccccc;
margin: 150px auto;
}
.inner{
width:490px;
height: 170px;
overflow: hidden;
position: relative;
}
ul{
list-style: none;
width:500%;
position: absolute;
left:0;
}
li{
float: left;
}
.square{
position: absolute;
bottom:10px;
right: 20px;;
}
span{
display: inline-block;
width: 16px;
height: 16px;
background-color: #fff;
text-align: center;
margin: 3px;
border:1px solid #cccccc;
line-height: 16px;
cursor: pointer;
}
.current{
background-color: darkorange;
color: #fff;
}
</style>
<script>
window.onload = function () {
var inner = document.getElementById("inner");
var ul = inner.children[0];
var spanArr = inner.children[1].children;
for(var i=0;i<spanArr.length;i++){
spanArr[i].index=i;
spanArr[i].function () {
for(var j=0;j<spanArr.length;j++){
spanArr[j].className="";
}
this.className="current";
//利用框架移动盒子(两个参数1.元素2.目标位置)
animate(ul,-this.index*490);
}
}
function animate(ele,target) {
clearInterval(ele.timer);
var speed=target>ele.offsetLeft?10:-10;
ele.timer=setInterval(function () {
var val=target-ele.offsetLeft;
ele.style.left=ele.offsetLeft+speed+"px";
if(Math.abs(val)<Math.abs(speed)){
ele.style.left=target+"px";
clearInterval(ele.timer);
}
},1);
}
}
</script>
</head>
<body>
<div class="box">
<div class="inner" id="inner">
<ul>
<li><img src="images/01.jpg" alt=""></li>
<li><img src="images/02.jpg" alt=""></li>
<li><img src="images/03.jpg" alt=""></li>
<li><img src="images/04.jpg" alt=""></li>
<li><img src="images/05.jpg" alt=""></li>
</ul>
<div class="square" >
<span class="current">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
</div>
</div>
</div>
</body>
</html>