JavaScript_banner輪播圖
讓我們一起來學習一下用js怎么實現banner輪播圖呢?
直接看代碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>banner輪播</title> <style> #banner{width:820px;height:430px;margin:0 auto;position:relative;} #banner img{width:100%;height:100%;} ul{position:absolute;top:83%;left:290px;list-style:none;} ul li{width:25px;height:25px;border-radius:50%;float:left;margin-right:15px;text-align:center;line-height:25px;} #Left,#Right{position:absolute;top:45%;width:60px;height:60px;display:none;} #banner:hover #Left{display:block;} #banner:hover #Right{display:block;} #Left{left:0;} #Right{right:0;} </style> </head> <!--頁面加載的時候直接加載它--> <body onload="lunbo()"> <div id="banner"> <img src="img/banner0.jpg" id="img"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <div id="Left"> <img src="img/07_箭頭_向左.png" id="left"> </div> <div id="Right"> <img src="img/07_箭頭_向右 (1).png" id="right"> </div> </div> <script type="text/javascript"> //首先我們要獲取到他們,便於接下來操作 var Img=document.getElementById("img"); var Lis=document.getElementsByTagName("li"); var Left=document.getElementById("left"); var Right=document.getElementById("right"); var index=-1; var Banner=document.getElementById("banner"); //定時器(需要定義的函數,它的毫秒數) var timer=setInterval("lunbo()",1800); //利用定時器使圖片達到輪播效果 function lunbo(){ index++; resetColor(); if(index == 4){ index=0; } Img.src="img/banner"+index+".jpg"; Lis[index].style.background="orchid"; } //小原點初始值顏色(定義函數,在定時器去調用它) function resetColor(){ for(var i=0;i<Lis.length;i++){ Lis[i].style.background="rgba(100,100,100,.5)"; } } //鼠標移入和移出 Banner.onmouseover=function(){ clearInterval(timer); } Banner.onmouseout=function(){ //變量作用域,因為這邊已經給它清除了,所以必須重新聲明它. timer=setInterval("lunbo()",1800); } //點擊小圓點切換圖片到指定位置 for (var i=0;i<Lis.length;i++) { Lis[i].onclick = function(){ clearInterval(timer); index = this.innerHTML-1; Img.src="img/banner"+index+".jpg"; resetColor(); Lis[index].style.background = "orchid"; timer = setInterval("lunbo()",1800); } } //左邊和右邊按鈕切換 Left.onclick = function(){ index--; if (index == -1) { index = 3; } Img.src="img/banner"+index+".jpg"; resetColor(); Lis[index].style.background = "orchid"; } Right.onclick = function(){ if (index == 3) { index = -1; } index++; Img.src="img/banner"+index+".jpg"; resetColor(); Lis[index].style.background = "orchid"; } </script> </body> </html>
希望對大家有幫助~~如果有更好的方法,可以一起學習交流哦!