头部样式表
<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>
body部分
<div class="box" id="box">
<div class="inner"><!--相框-->
<ul>
<li><a href="#"><img src="10简单的轮播图/images/1.jpg" alt=""/></a></li>
<li><a href="#"><img src="10简单的轮播图/images/2.jpg" alt=""/></a></li>
<li><a href="#"><img src="10简单的轮播图/images/3.jpg" alt=""/></a></li>
<li><a href="#"><img src="10简单的轮播图/images/4.jpg" alt=""/></a></li>
<li><a href="#"><img src="10简单的轮播图/images/5.jpg" alt=""/></a></li>
<li><a href="#"><img src="10简单的轮播图/images/6.jpg" alt=""/></a></li>
</ul>
<div class="square">
<span class="current">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
</div>
</div>
</div>
<script>
//获取最外面的div
var box = document.getElementById("box");
//获取相框也可以看成是 容器
var inner = box.children[0];
//获取相框的宽度
var imgWitdh =inner.offsetWidth;
//获取ul
var ulObj = inner.children[0];
//获取小按钮 span
var spanObjs = inner.children[1].children;
//循环遍历所有的span标签,注册鼠标进入的事件
for (var i = 0 ;i<spanObjs.length;i++){
//循环的时候把索引值保存在每个span的自定义属性中
spanObjs[i].setAttribute("index",i);
//循环的时候把索引值保存在每个span的自定义属性中
spanObjs[i].setAttribute("index",i);
//注册鼠标进入事件
spanObjs[i].onmouseover=function () {
//排他功能,先把所有span颜色去掉
for (var j = 0;j<spanObjs.length;j++){
//移除了每个span的类样式
spanObjs[j].removeAttribute("class");
}
//设置当前的span的背景颜色
this.className="current";
//移动ul(每个图片的宽*鼠标放在这个按钮的索引值)
//获取当前鼠标进入的span索引
var index = this.getAttribute("index");
animate(ulObj,-index*imgWitdh);
animate()
}
};
//下面这个是封装的动画代码
function animate(element,target) {
//先把定时器清理掉
clearInterval(element.timeId);
//清理定时器(只产生一个定时器)
element.timeId = setInterval(function () {
//获取当前div的位置
var current = element.offsetLeft;//数字类型 ,没有px
//div每次移动多少像素---步数
var step = 10;
step=current<target?step:-step;
//每次移动后的距离
current+=step;
//判断当前移动后的位置是否达到目标位置
if(Math.abs(target - current)>Math.abs(step)){
element.style.left = current + "px";
}else {
//清理定时器
clearInterval(element.timeId);
element.style.left=target+"px";
}
},20);
}
</script>