思路:將想要播放的圖片放入集合中,設置一個div,將圖片依次從集合中定時取出放到div中展示;設置一個變量,通過變量與集合元素索引聯系起來,點擊改變時,獲取當前圖片的索引以切換圖片
整體代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>圖片輪播</title> <style> *{margin:0px auto; padding:0px;} #kuangjia {width:600px; height:450px; border:#F00 solid 3px; background-size:cover; background-repeat:no-repeat;} .t1 {width:40px; height:40px; background-repeat:no-repeat; background-size:contain; cursor:pointer;} #t2 {float:left; margin:205px 0px 0px 20px; background-image:url(zuo.png);} #t3 {float:right; margin:205px 20px 0px 0px; background-image:url(you.png);} </style> </head> <body> <div id="kuangjia"><!--大div作為框架--> <div class="t1" id="t2" onclick="(dd(-1))"></div> <div class="t1" id="t3" onclick="(dd(1))"></div> </div> </body> </html> <script> var jh=new Array(); jh[0]="url(1-1.jpg)"; jh[1]="url(2-2.jpg)"; jh[2]="url(3-3.jpg)"; jh[3]="url(4-4.jpg)"; jh[4]="url(5-5.jpg)"; var kj=document.getElementById("kuangjia");<!--獲取框架div的標簽,在下面進行更改背景--> var x=-1;<!--定義變量x,建立索引--> var l=jh.length;<!--獲取集合中元素個數--> function lb() { x++; if (x==l) { x=0; } kj.style.backgroundImage=jh[x]; window.setTimeout("lb()",2000);<!--2s后再次播放集合中的圖片--> } window.setTimeout("lb()",0);<!--開始進行輪播--> function dd(m) { x=x+m; if(x==l) {x=0;} else if(x==-1) {x=l;} kj.style.backgroundImage=jh[x]; } </script>
下面為步驟及分步代碼:
1、設置大div框架及向左向右按鈕

<title>圖片輪播</title> <style> *{margin:0px auto; padding:0px;} #kuangjia {width:600px; height:460px; border:#F00 solid 3px; background-size:contain; background-repeat:no-repeat;} .t1 {width:60px; height:60px; background-repeat:no-repeat; background-size:contain;} #t2 {float:left; margin:200px 0px 0px 20px; background-image:url(zuo.png);} #t3 {float:right; margin:200px 20px 0px 0px; background-image:url(you.png);} </style> </head> <body> <div id="kuangjia"><!--大div作為框架--> <div class="t1" id="t2"></div> <div class="t1" id="t3"></div> </div> </body>
2、定義一個集合,將要播放的圖片放入集合

</html> <script> var jh=new Array(); jh[0]="url(1-1.jpg)"; jh[1]="url(2-2.jpg)"; jh[2]="url(3-3.jpg)"; jh[3]="url(4-4.jpg)"; jh[4]="url(5-5.jpg)"; </script>
3、設置自動播放功能:每隔2s切換一張圖()

var kj=document.getElementById("kuangjia");<!--獲取框架div的標簽,在下面進行更改背景--> var x=-1;<!--定義變量x,建立索引--> var l=jh.length;<!--獲取集合中元素個數--> function lb() { x++; if (x==l) { x=0; } kj.style.backgroundImage=jh[x]; window.setTimeout("lb()",2000);<!--2s后再次播放集合中的圖片--> } window.setTimeout("lb()",0);<!--開始進行輪播--> </script>
4、建立點擊左或右進行切圖事件

body中 <div id="kuangjia"><!--大div作為框架--> <div class="t1" id="t2" onclick="(dd(-1))"></div> <div class="t1" id="t3" onclick="(dd(1))"></div> </div> </html>后 function dd(m) { x=x+m; if(x==l) {x=0;} else if(x==-1) {x=l;} kj.style.backgroundImage=jh[x]; }
點左按鈕變量-1,判斷是否小於0,如果小於0則讓x=l;點右按鈕變量+1,如果等於l,則讓x=0