使用JQuery制作幻灯片(轮播图)
1.首先看一下目录结构
images文件夹放所需要播放的图片。
js文件夹放jquery库和main.js
2.html代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>JQuery slideShow</title> 6 <style> 7 *{margin: 0;padding: 0} 8 ul,ol{list-style: none;} 9 .slideShow{position: relative;margin: 100px auto;height: 140px;width: 340px;overflow: hidden;} 10 .slideShow ul{ position: relative;width: 2000px; } 11 .slideShow ul li{float: left;width: 340px} 12 .slideShow .nav{text-align: center;position: absolute;right: 10px;bottom: 10px;font-size: 12px;line-height: 18px;} 13 .slideShow .nav span{ -webkit-user-select:none;user-select:none;float: left;cursor: pointer;border-radius: 9px;display: inline-block;width: 18px;height: 18px;background:rgba(0,0,0,0.7);margin-left: 2px;color: #fff;opacity: 0.5;} 14 .slideShow .nav span.active{opacity: 1;} 15 </style> 16 </head> 17 <body> 18 <div class="slideShow"> 19 <ul> 20 <li><a href="#"><img src="./images/01.jpg" alt=""></a></li> 21 <li><a href="#"><img src="./images/02.jpg" alt=""></a></li> 22 <li><a href="#"><img src="./images/03.jpg" alt=""></a></li> 23 <li><a href="#"><img src="./images/04.jpg" alt=""></a></li> 24 <li><a href="#"><img src="./images/05.jpg" alt=""></a></li> 25 </ul> 26 <div class="nav"> 27 <span class="active">1</span> 28 <span>2</span> 29 <span>3</span> 30 <span>4</span> 31 <span>5</span> 32 </div> 33 <script src="js/jquery-3.1.1.min.js"></script> 34 <script src="js/main.js"></script> 35 </body> 36 </html>
3.main.js代码:
1 $(document).ready(function(){ 2 var slideShow = $(".slideShow"), //获取div 3 ul=slideShow.find("ul"), 4 nav=slideShow.find(".nav span"), //获取按钮 5 oneWidth=ul.find("li").eq(0).width(), 6 timer=null, 7 iNow=0; 8 slideShow.hover(function(){ 9 clearInterval(timer); 10 },autoPlay); 11 12 nav.on("click",function(){ //添加点击按钮 13 var me=$(this), 14 index=me.index(); 15 iNow=index; 16 ul.animate({ 17 "left":- oneWidth * iNow, 18 }); 19 nav.removeClass("active"); 20 me.addClass("active"); 21 }); 22 23 autoPlay(); 24 function autoPlay(){ 25 timer = setInterval(function(){ 26 iNow++; 27 if(iNow>nav.length-1){ 28 iNow=0; 29 } 30 nav.eq(iNow).trigger("click"); 31 },2000); 32 } 33 });
4.效果图
当然了,大小可以利用CSS自己进行调整!
声明:代码非原创,取自网络。