<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>圖片輪播</title> <style> *{ padding:0;margin:0; } #demo{ position:relative; width:730px; height:454px; margin:100px auto; } #pic{ width:730px; height:454px; } .ig{ position: absolute; } .but{ width:30px; height:54px; color:#fff; background:rgba(0,0,0,0.5); font-size:40px; text-align: center; line-height: 54px; cursor:pointer; position: absolute; top:50%; margin-top:-27px; } #leftBut{ left:0; } #rightBut{ right:0; } span{ display: inline-block; width:30px; height:30px; background-color: #fff; color:#0f0f0f; cursor:pointer; position: relative; top:-50px; left:300px; text-align: center; line-height: 30px; border-radius: 50%; } .bg{ background-color: red; } </style> <script src="jquery-3.0.js"></script> </head> <body> <div id="demo"> <div id="pic"> <img class="ig" src="img/1.jpg" alt=""> <img class="ig" src="img/2.jpg" alt=""> <img class="ig" src="img/3.jpg" alt=""> <img class="ig" src="img/4.jpg" alt=""> </div> <div id="leftBut" class="but">‹</div> <div id="rightBut" class="but">›</div> <div id="num"> <span class="bg">1</span> <span>2</span> <span>3</span> <span>4</span> </div> </div> <script> var i=0; var timer; $(function () { $(".ig").eq(0).show().siblings().hide();//第一張圖顯示,其他隱藏 showTime(); $("span").hover(function () { i=$(this).index(); show(); clearInterval(timer) },function () { showTime(); }); $("#leftBut").click(function () { clearInterval(timer); if(i==0){ i=4 } i--; show(); showTime(); }); $("#rightBut").click(function () { clearInterval(timer); if(i==3){ i=-1 } i++; show(); showTime(); }); }); function show() { $(".ig").eq(i).fadeIn(300).siblings().fadeOut(300);//第i張圖片顯示,其他隱藏 $("span").eq(i).addClass("bg").siblings().removeClass("bg");//數字按鈕跟隨圖片顯示樣式 } function showTime() {//每隔3秒,i+1,並執行show函數 timer=setInterval(function () { i++; if(i==4){ i=0; } show(); },3000); } </script> </body> </html>