<style>
* {
margin: 0;
padding: 0
}
ul {
list-style: none
}
img {
vertical-align: top
}
.box {
width: 730px;
height: 454px;
margin: 100px auto;
padding: 5px;
border: 1px solid #ccc;
}
.inner {
width: 730px;
height: 454px;
background-color: pink;
overflow: hidden;
position: relative;
}
.inner ul {
width: 1000%;
position: absolute;
top: 0;
left: 0;
}
.inner li {
float: left;
}
.square {
position: absolute;
right: 10px;
bottom: 10px;
}
.square span {
display: inline-block;
width: 16px;
height: 16px;
background-color: #fff;
text-align: center;
line-height: 16px;
cursor: pointer;
}
.square span.current {
background-color: orangered;
color: #fff;
}
</style>
//获取最外面的div
var box=myTab("box");
//获取相框
var inner=box.children[0];
//获取相框的宽度
var imgWith=inner.offsetWidth;
//获取ul
var ul=inner.children[0];
//获取小方块
var span=inner.children[1].children;//所有的span
//循环所有的span标签,注册鼠标移入事件
for(var i=0;i<span.length;i++){
//把索引值保存到每一个span里
span[i].setAttribute("index",i);
span[i].onmouseover=function () {
//去掉所有的span背景颜色
for(var j=0;j<span.length;j++){
span[j].removeAttribute("class");
}
//给当前的span的背景颜色
this.className="current";
//获取当前span的索引值
var index=this.getAttribute("index");
//调用动画函数
animate(ul,-index*imgWith);
}
}
function animate(ele,target) {
//先清理定时器
clearInterval(ele.timeId);
//ele.timeId 定时器的Id
ele.timeId = setInterval(function () {
//获取当前的位置
var current = ele.offsetLeft;
//设置div每次移动多少px
var st = 9;
//判断向左移还是右移动
st = current < target ? 9 : -9;
//每次移动后的距离
current += st;
//判断移动后的位置是否到达目标位置
if (Math.abs(target - current) > Math.abs(st)) {
//设置div的left值
ele.style.left = current + "px";
} else {
//清除定时器
clearInterval(ele.timeId);
//将目标位置设置为div的值
ele.style.left = target + "px";
}
}, 10);
}