原生JS-实现轮播图
用原生JS实现一个轮播图(效果)
HTML
<div id="outer"> <ul id="imgList"> <!-- 图片列表 --> <li><img src="p1.jpg"/></li> <li><img src="p2.jpg"/></li> <li><img src="p3.jpg"/></li> <li><img src="p4.jpg"/></li> <li><img src="p5.jpg"/></li> <li><img src="p1.jpg"/></li> </ul> <!-- 导航按钮 --> <div id="navDiv"> <a href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> </div> </div>
CSS
*{ margin: 0; padding: 0; } #outer{ width: 740px; height: 450px; margin: 50px auto; background-color:skyblue ; padding: 10px 0; position: relative; overflow: hidden; } #imgList{ list-style: none; position: absolute; /* 偏移量 */ /* left: -740px; */ } #imgList li{ float: left; margin: 0 10px; } #navDiv{ position: absolute; bottom: 15px; left: 307px; } #navDiv a{ float: left; width: 15px; height: 15px; background-color: red; margin: 0 5px; opacity: 0.5; } #navDiv a:hover{ background-color: black; }
JavaScript
window.onload = function(){ var imgList = document.getElementById('imgList'); var imgArr = document.getElementsByTagName('img'); var navDiv = document.getElementById('navDiv'); var outer = document.getElementById('outer'); var allA = document.getElementsByTagName('a'); //设置imgList的宽度 imgList.style.width = 740 * imgArr.length + 'px'; //设置导航按钮居中 navDiv.style.left = (outer.offsetWidth -navDiv.offsetWidth)/2 + 'px'; var index = 0; var timer; allA[index].style.backgroundColor = 'black'; for(var i = 0;i<allA.length;i++){ //给allA添加num属性,储存i索引 allA[i].num = i; allA[i].onclick = function(){ clearInterval(timer); index = this.num; setA(); move(imgList,'left',-740*index,20,function(){ autoChang(); }) } }; autoChang(); //设置导航按钮颜色 function setA(){ //判断index 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 = 'black'; }; //自动轮播 function autoChang(){ timer = setInterval(function(){ index++; index %= imgArr.length; move(imgList,'left',-740*index,20,function(){ setA(); }); },3000) } //获取obj当前样式 function getStyle(obj,name){ if(window.getComputedStyle){ return getComputedStyle(obj ,null)[name]; }else{ return obj.currentStyle[name]; } }; //切换图片 function move(obj,att,target,speed,callback){ clearInterval(obj.timer); var current = parseInt(getStyle(obj,att)); if(current > target){ speed = -speed; } obj.timer = setInterval(function(){ var oldValue = parseInt(getStyle(obj,att)); var newValue = oldValue + speed; if((speed < 0 && newValue < target) || (speed > 0 && newValue > target)){ newValue = target; } obj.style[att] = newValue +'px'; if(newValue == target){ clearInterval(obj.timer); callback && callback(); } },30) } }
PS:
//添加属性
allA[i].num = i;
//函数的封装
move(obj,att,target,speed,callback)、getStyle(obj,att)
//回调函数
callback
//函数的调用
autoChang();