jQuery之焦点图转换-左右
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>焦点图转换</title> 6 <link rel="stylesheet" href="css/reset.css"> 7 <style type="text/css"> 8 .pic-show{width: 480px;overflow: hidden;} 9 .pic{width: 1920px;height: 320px;position: relative;} 10 .pic img{display: block;float: left;} 11 .pic-show>img{display: block;cursor: pointer;opacity: 0.8; position: absolute;top: 142px;left: 30px;} 12 .pic-show>img:last-child{display: block; position: absolute;left: 414px; } 13 ul{width: 120px;height: 18px;position: absolute;top: 280px;left: 185px;} 14 li{float: left;width: 20px;height: 18px;margin-left: 5px;} 15 a{display: block;width: 20px;height: 18px;text-decoration: none;border: 1px solid #ccc;border-radius: 50%;background-color: #ccc;opacity: 0.6;} 16 a:hover{background-color: #094a99;} 17 .aCss{background-color: #094a99;} 18 p{width: 480px;text-align: center;} 19 20 </style> 21 </head> 22 <body> 23 <div class="pic-show"> 24 <div class="pic"> 25 <img src="images/1.jpg" alt=""> 26 <img src="images/2.jpg" alt=""> 27 <img src="images/3.jpg" alt=""> 28 <img src="images/4.jpg" alt=""> 29 </div> 30 <img class="prev" src="images/slider-prev.png" alt=""> 31 <img class="next" src="images/slider-next.png" alt=""> 32 </div> 33 <ul> 34 <li><a class="aCss" href="#" title="日落"></a></li> 35 <li><a href="#" title="钢琴"></a></li> 36 <li><a href="#" title="大海"></a></li> 37 <li><a href="#" title="秋色"></a></li> 38 </ul> 39 <p>这是一段测试文字</p> 40 <script src="js/jquery-3.0.0.js"></script> 41 <script type="text/javascript"> 42 var num=0;//定义num,以便点击左右按钮时得到0,1,2,3这四个值来找到图片
//点击next按钮 43 $(".pic-show .next").click(function(event){ 44 if(num<3){ 45 num=num+1; 46 } 47 else{ 48 num=0; 49 } 50 console.log(num); 51 var mlNum=num * -480+'px'; 52 $(".pic").animate({"margin-left":mlNum},1000) 53 $("ul li:eq("+num+") a").addClass("aCss").parent().siblings().find("a").removeClass("aCss"); 54 event.preventDefault(); 55 var txt=$("ul li").eq(num).find("a").attr("title"); 56 console.log(txt); 57 $("p").text(txt); 58 })
//点击prev按钮 59 $(".pic-show .prev").click(function(event){ 60 if(num>0){ 61 num=num-1; 62 } 63 else{ 64 num=3; 65 } 66 console.log(num); 67 var mlNum2=num * -480+'px'; 68 $(".pic").animate({"margin-left":mlNum2},1000) 69 $("ul li").eq(num).find("a").addClass("aCss").parent().siblings().find("a").removeClass("aCss"); 70 event.preventDefault(); 71 var txt=$("ul li").eq(num).find("a").attr("title"); 72 console.log(txt); 73 $("p").text(txt); 74 }) 75 $("ul li a").click(function(event){ 76 num=$(this).parent().index(); 77 var mlNum3=num * -480+'px'; 78 $(".pic").animate({"margin-left":mlNum3},500) 79 80 $(this).addClass("aCss").parent().siblings().find("a").removeClass("aCss");//addClass 81 event.preventDefault(); 82 83 var txt=$(this).attr("title"); 84 console.log(txt);//测试用 85 $("p").text(txt); 86 }) 87 </script> 88 89 </body> 90 </html>
左右转换需要在实现左右转换的同时实现点击换图,这样就需要(num=index;即红色部分。),详解见代码。