<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
img {
vertical-align: top;
}
.box {
width: 730px;
height: 454px;
padding: 5px;
margin: 100px auto;
border: 1px solid #ccc;
}
.inner {
width: 730px;
height: 454px;
background-color: #0099cc;
position: relative;
overflow: hidden;
}
.inner ul {
position: absolute;
top: 0;
left: 0;
width: 1000%;
}
.inner li {
float: left;
}
.square {
position: absolute;
right: 10px;
bottom: 10px;
}
.square span {
display: inline-block;
width: 16px;
height: 16px;
text-align: center;
line-height: 16px;
background-color: #ffffff;
cursor: pointer;
}
.square span.current {
background-color: coral;
color: #ffffff;
}
</style>
</head>
<body>
<div class="box" id="box">
<!--相框-->
<div class="inner">
<ul>
<li><a href="#" ><img src="images/1.jpg" alt=""/></a></li>
<li><a href="#" ><img src="images/2.jpg" alt=""/></a></li>
<li><a href="#" ><img src="images/3.jpg" alt=""/></a></li>
<li><a href="#" ><img src="images/4.jpg" alt=""/></a></li>
<li><a href="#" ><img src="images/5.jpg" alt=""/></a></li>
<li><a href="#" ><img src="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 src="../common.js"></script>
<script>
//获取各个子元素的对象
var boxobj=my$("box");
var innerobj=boxobj.children[0];
//获取innerobj,也就是相框的宽度,这里是非常重要的,记住一定是inner
var phwidth=innerobj.offsetWidth;
var ulobj=innerobj.children[0];
var squareobj=innerobj.children[1];
var spanobj=squareobj.children;
//遍历span,为其添加鼠标事件
for(var i=0;i<spanobj.length;i++){
//因为要获取小图标的下标,但是事件触发的时候,循环已经遍历完了,所以遍历的时候要添加下标属性
spanobj[i].setAttribute("index",i);
spanobj[i].onmouseover=function(){
//点那个,小图标背景颜色改变,这里使用排他功能
for( var j=0;j<spanobj.length;j++){
spanobj[j].removeAttribute("class");
}
this.className="current";
//获取index属性
var index=this.getAttribute("index");
move(ulobj,-index*phwidth);
console.log(-index*phwidth);
}
}
//图片的移动使用动画移动封装函数
function move(element, target) {
//第二个坑,每点一次按钮就出现一个定时器,容易造成越点越快,所以搜先要清理之前的定时器,保证只存在一个定时器。
clearInterval(element.timeid);
//timeid之前是一个变量,现在定义为element的一个属性,这样无论开多少定时器,timeid内存只占一个,不会开辟新的内存空间。
element.timeid = setInterval(function () {
var current = element.offsetLeft;
var step = 10;
step = target - current > 0 ? step : -step;
//每次移动后的距离
current += step;
//第一个坑
//判断移动后的距离是否到达目标位置
if (Math.abs(target - current) > Math.abs(step)) {
//显示移动后的距离,但是要考虑最后马上到的距离。
element.style.left = current + "px";
} else {
//如果距离小于10,就直接到目标点。
clearInterval(element.timeid);
element.style.left = target + "px";
}
}, 20);
}
</script>
</body>
</html>
![](https://img.haomeiwen.com/i13694129/62354099d08d4511.png)
轮播图实现效果图
网友评论