近來時間有些閑暇,有空寫一些東西了,從輪播圖開始,就這么愉快的決定了,現在把我前天寫的一個漸變方式的輪播分享出來,望大家給指導意見。
輪播嘛,幾乎每個網站都有,幾張大圖,放一些醒目的活動或者公告,用戶一眼就能看到。漸變方式的要比滑動方式的簡單一點,因為它前后不需要前一頁或下一頁來銜接,它的原理也很簡單,圍繞圖片的索引,依靠索引來切換。有難度一點的地方可能就在於索引是最后一張的時候要讓它切到索引為0,以及點擊左邊按鈕和點擊右邊按鈕都能順利切換,還有注意的一點是,每張圖片定位在同一位置,這樣漸變不會閃白。好了,下面上代碼。
HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>輪播</title> <script src="js/jquery-1.8.3.min.js"></script> <script src="js/lunbo.js"></script> <link rel="stylesheet" href="css/lunbo.css" /> </head> <body> <div class="wrap"> <div class="btnBox"> <span id="left"><</span> <span id="right">></span> </div> <div class="wraps"> <img src="images/photo-1.jpg" /> <img src="images/photo-2.jpg" /> <img src="images/photo-3.jpg" /> </div> <p class="page"></p> </div> </body> </html>
CSS:
*{ margin:0; padding:0; } .wrap{ width:400px; height: 300px; overflow: hidden; position: relative; } .wraps{ width:1200px; height: 300px; } .wraps img{ float: left; cursor: pointer; position: absolute; top:0; left:0; } .page{ position: absolute; bottom:10px; right:10px; } .page span{ float: left; width:20px; height: 20px; text-align: center; line-height: 20px; background: rgba(0, 0, 0, 0.5); color: #fff; margin-left:10px; cursor: pointer; } .page span.current{ background: rgba(0, 0, 0, 0.8); } .btnBox span{ width:30px; height: 30px; display: inline-block; background: rgba(0, 0, 0, 0.5); color: #fff; font-size: 20px; text-align: center; line-height: 26px; cursor: pointer; position: absolute; top:50%; margin-top:-10px; z-index: 3; } #left{ left:0; } #right{ right:0; }
jQuery:
$(function(){ $(".wraps img:not(:first)").hide(); var index = 0; var s = $(".wraps img").length; var auto; for(var i=1; i<=s; i++){ $(".page").append("<span>" + i + "</span>"); } $(".page span:first").addClass("current"); $(".page span").on("click", function(){ index = $(this).index(); move(); }); function autos(){ auto = setInterval(function(){ index++; if(index == s){ index = 0; } move(); }, 3000); } autos(); function move(){ $(".page span").eq(index).addClass("current").siblings().removeClass('current'); $(".wraps img").eq(index).stop(true, true).fadeIn().siblings().stop(true, true).fadeOut(); } $("#left").click(function(){ clearInterval(auto); index--; if(index <= -1){ index = s-1; } move(); autos(); }); $("#right").click(function(){ clearInterval(auto); index++; if(index >= s){ index = 0; } move(); autos(); }); $(".wraps img, .page span").mouseover(function(){ clearInterval(auto); }).mouseout(function(){ autos(); }); });