<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
body,ul,ol,li,img{margin:0;padding:0;list-style:none;}
#box{width:490px;height:170px;padding:5px;
position: relative;border:1px solid #ccc;margin:100px auto 0;overflow:hidden;}
.ad{width:490px;height:170px;overflow:hidden;position:relative;}
#box img{width:490px;}
.ad ol{position:absolute;right:10px;bottom:10px;}
.ad ol li{width:20px;height:20px;line-height:20px;border:1px solid #ccc;text-align:center;background:#fff;float:left;margin-right:10px;cursor:pointer;_display:inline;}
.ad ol li.current{background:yellow;}
.ad ul li{float:left;}
.ad ul{ position:absolute; top:0; width:2940px;}
.ad ul li.current{display:block;}
#arr { display: none;}
#arr span{ width:40px; height:40px; position:absolute; left:5px; top:50%; margin-top:-20px; background:#000; cursor:pointer; line-height:40px; text-align:center; font-weight:bold; font-family:'黑体'; font-size:30px; color:#fff; opacity:0.3; border:1px solid #fff;}
#arr #right{right:5px; left:auto;}
</style>
</head>
<body>
<div id="box" class="all">
<div class="ad">
<ul id="imgs">
<li><img src="images/01.jpg" /></li>
<li><img src="images/02.jpg" /></li>
<li><img src="images/03.jpg" /></li>
<li><img src="images/04.jpg" /></li>
<li><img src="images/05.jpg" /></li>
</ul>
</div>
<div id="arr">
<span id="left"><</span>
<span id="right">></span>
</div>
</div>
<script>
//需求:鼠标放在盒子上面显示左右按钮
var box=document.getElementById("box");
var imgWidth=box.children[0].offsetWidth;
var ul=box.children[0].children[0];
var boxleftRight=box.children[1];
var btnArr=boxleftRight.children;
box.function () {
boxleftRight.style.display="block";
}
box.function () {
boxleftRight.style.display="none";
}
//点击右侧盒子图片做移动并用计数器模拟index值
//定义计数器
var index=0;
btnArr[1].function () {
index++;
if(index>ul.children.length-1){
index=ul.children.length-1;
}
animate(ul,-index*imgWidth);
}
//点击左侧盒子图片做移动并用计数器模拟index值
btnArr[0].function () {
index--;
if(index<0){
index=0;
}
animate(ul,-index*imgWidth);
}
//函数封装
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>
</body>
</html>
函数封装
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);
}