利用定时器Interval实现轮播图的笔记
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#outer{
width: 520px;
height: 281px;
margin: 0 auto;
margin-top: 50px;
background-color: #ADFF2F;
padding: 10px 0;
position: relative;
overflow: hidden;
}
#imgList{
list-style: none;
width: 1560px;
/* 给子元素设置绝对定位要给父元素设置相对定位 */
position: absolute;
}
#imgList li{
float: left;
padding: 0 10px;
}
#navDiv{
position: absolute;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
}
#navDiv a{
float: left;
width: 15px;
height: 15px;
background-color: #FAEBD7;
margin: 0 5px;
/* 透明 */
opacity: 0.5;
/* 给透明设置IE8兼容 */
filter: alpha(opacity=50);
}
#navDiv a:hover{
background-color: cadetblue;
}
</style>
<script type="text/javascript" src="js/tools.js"></script>
<script type="text/javascript">
/*
*
*/
window.onload = function(){
var imgList = document.getElementById("imgList");
var imgArr = document.getElementsByTagName("img");
imgList.style.width = 520 * imgArr.length + "px";
// 默认显示图片的索引
var index = 0;
var allA = document.getElementsByTagName("a");
allA[index].style.backgroundColor = "cadetblue";
// 点击超链接切换到指定图片
for(var i = 0;i < allA.length; i++){
allA[i].num = i;
allA[i].onclick = function(){
clearInterval(timer)
index =this.num;
imgList.style.left = index*(-520) + "px";
// 修改正在选中的a
setA();
move(imgList,"left",-520*index,20,function(){
autoChange()
})
}
}
// 开启自动切换
var timer;
function autoChange(){
timer = setInterval(function(){
// 使索引自增
index++;
// 判断index的值
index %= imgArr.length;
move(imgList,"left",-520*index,20,function(){
setA();
})
},3000)
}
function setA(){
if(index >= imgArr.length-1){
index = 0;
imgList.style.left = 0;
}
for(var i = 0; i<allA.length;i++){
allA[i].style.backgroundColor = "";
}
allA[index].style.backgroundColor = "cadetblue";
}
autoChange();
}
</script>
</head>
<body>
<div id="outer">
<ul id="imgList">
<li><img src="img/01.jpg" ></li>
<li><img src="img/04.jpg" ></li>
<li><img src="img/05.jpg" ></li>
<li><img src="img/01.jpg" ></li>
</ul>
<!-- 创建导航按钮 -->
<div id="navDiv">
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</div>
</div>
</body>
</html>
**
## **导入的js文件:**
**
// 获取样式的函数
function getStyle(obj,name){
// 正常浏览器的方式
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
// IE8的方式
return obj.currentStyle[name]
}
}
// 定时器实现动画效果
function move(obj,attr,target,speed,callback){
/*
参数:
obj :要执行动画的对象
attr:要执行的样式(left、top、width、height)
target:执行动画的目标位置
speed:移动的速度(正数向右,负数向左)
callback:回调函数
*/
clearInterval(obj.timer);
var current =parseInt(getStyle(obj,attr));
if(current > target){
speed = -speed;
}
// 开启定时器
obj.timer = setInterval(function(){
var oldValue = parseInt(getStyle(obj,attr));
//设置步长,每次偏移距离
var newValue = oldValue + speed;
if((speed < 0 && newValue < target) || (speed > 0 && newValue > target)){
newValue = target;
};
obj.style[attr] = newValue + "px";
if(newValue == target){
clearInterval(obj.timer)
callback && callback();
};
},30);
};