javaScript学习总结——图片轮播
示例代码:
<html> <head> <!--http://www.jb51.net/article/64662.htm --> <style type="text/css"> body{ margin:0px; <!--这两句必写,避免在不同浏览器中显示时发生错位--> padding:0px; } img{ width:320px;height:200px;} ul li{ list-style:none; float:left; padding:5px; margin-right:5px; border:1px solid gray; } ul{ position:relative; margin-right:10px; margin-top:20px; } .dq{ background-color:red; color:white; } </style> </head> <body> <div id="imglunbo"> <img id="imgDemo" src= "1.jpg"/> </div> <script> //把数字弄出来 var imgs = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"]; //依据图片数组的数量,创建一个ul。里面包含数组数量的li function createImageNums(){ var myul = document.createElement("ul"); for(var i=1;i <= imgs.length;i++){ var myli = document.createElement("li"); var mynum = document.createTextNode(i); if(i==1){ myli.setAttribute("class","dq"); } myul.appendChild(myli); myli.appendChild(mynum); //因为要实现点击li时,理解切换 //所以这里给li添加了一个onclick单击事件 myli.onclick = qiehuan; } var imglunbo = document.getElementById("imglunbo"); imglunbo.appendChild(myul); } //createImageNums end createImageNums(); //自动切换图片 var currentIndex = 0;//当前的图片在数组中的索引值 function changeImg(){ var myimg = document.getElementById("imgDemo"); myimg.src = imgs[currentIndex]; changestyle(currentIndex); currentIndex++; //因为不断增加会导致索引越界,所以需要归0 if(currentIndex==imgs.length){ currentIndex = 0; } } function changestyle(num){ var allli=document.getElementsByTagName("li"); for(var i=0;i<allli.length;i++){ allli[i].setAttribute("class",""); } allli[num].setAttribute("class","dq"); } var autoChange = setInterval(changeImg,3000); //3.点击数字时,立即切换图片 // 切换成功之后,自动切换图片的功能还能生效 function qiehuan(){ //假定10秒自动,此时刚切换图片之后 //过了3秒,如果点击数字切换,不清掉定时器 //就会导致7秒之后又自动切换 clearInterval(autoChange); var clickedNum = parseInt(this.innerText); currentIndex = clickedNum-1; console.log(currentIndex); changeImg(); autoChange = setInterval(changeImg,3000); } </script> </body> </html>
运行结果:
时间: 2024-10-18 14:51:00