用js代码来实现一个简单的图片轮播效果
鼠标移入图片后显示左右箭头按钮,点击就可以实现图片的切换。
以下分别是html代码和js代码,欢迎批评和讨论!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片轮播</title> <style> *{padding:0px; margin:0px;} ul{ position: absolute; left:0px; top:0px; list-style-type:none; width:2600px; height:280px; } ul li{ width:520px; height:280px; float:left; } #box{ position:relative; width:520px; height:280px; margin:50px auto; overflow:hidden; } #btn div{ position: absolute; width:20px; height:40px; background:lightskyblue; top:120px; line-height: 40px; text-align:center; opacity:0.5; filter:alpha(opacity:30); display:none; } #Rbtn{ left:500px; } </style> </head> <body> <div id="box"> <ul id="ul"> <li><img src="imgs/1.jpg" alt=""></li> <li><img src="imgs/2.jpg" alt=""></li> <li><img src="imgs/3.jpg" alt=""></li> <li><img src="imgs/4.jpg" alt=""></li> <li><img src="imgs/5.jpg" alt=""></li> </ul> <div id="btn"> <div id="Lbtn"><</div> <div id="Rbtn">></div> </div> </div> <script src="js/animate.js"></script> <script src="js/myJs.js"></script> </body> </html>
var ul = document.getElementById("ul"), lis = document.getElementsByTagName("li"), box = document.getElementById("box"), lbtn = document.getElementById("Lbtn"), rbtn = document.getElementById("Rbtn"); //还有一个问题,左键可以无限点击,但是右键必须等待效果执行完毕才可以继续点击 lbtn.onclick = function(){ ul.insertBefore(ul.lastElementChild,lis[0]); ul.style.left = "-520px"; animate(ul,0,"left"); } rbtn.onclick = function(){ animate(ul,-520,"left",function(){ ul.appendChild(ul.firstElementChild); //注意这里firstChild和firstElementChild是不同的,firstChild是text对象,不能直接拿走图片 ul.style.left="0px"; //因为把往左拉的第一张图片重新放在最后了,因此将left的值重新设置为0 }); } box.onmouseover = function(){ lbtn.style.display = "block"; rbtn.style.display = "block"; } box.onmouseout = function(){ lbtn.style.display = "none"; rbtn.style.display = "none"; }
1 //回调函数,重新调用自身,但是此时注意,第四个参数不可以直接调用animate,因为animate函数中调用fn时,并没有带上任何参数 2 3 function animate(dom,target,attr,fn){ 4 clearInterval(dom.timer); 5 dom.timer = setInterval(function(){ 6 var domAttr = parseFloat(getAttr(dom,attr)); 7 var speed = (target - domAttr)/10; 8 console.log(speed); 9 if(attr == "opacity"){ 10 domAttr *= 100; 11 } 12 13 if(target>domAttr){ 14 speed = Math.ceil(speed); 15 }else{ 16 speed = Math.floor(speed); 17 } 18 if(target == domAttr){ 19 clearInterval(dom.timer); 20 //进行判断,当没有第四个参数,即不需要回调函数时,则不执行 21 if(fn){ 22 //当重复调用时,this的指向会改变,因此要在dom的作用域下调用fn函数才不会出错 23 fn.call(dom); 24 } 25 }else{ 26 if(attr=="opacity"){ 27 dom.style[attr] = (domAttr + speed)/100; 28 dom.style.filter = "alpha(opacity:"+(domAttr + speed)+");" 29 }else{ 30 dom.style[attr] = domAttr + speed +"px"; 31 } 32 } 33 },30); 34 } 35 36 function getAttr(dom,attr){ 37 if(dom.currentStyle){ 38 return dom.currentStyle[attr]; 39 }else{ 40 return getComputedStyle(dom,null)[attr]; 41 } 42 }