以下程式碼對學習 jQuery 的朋友是個不錯的參考,示範如何做出「點擊小圖、大圖切換」的輪播效果。

<div class="warp" id="warp">
<img src="pic1.bmp" alt="" class="imgBig" />
<img src="pic2.bmp" alt="" class="imgLittle" />
<img src="pic3.bmp" alt="" class="imgLittle" />
<img src="pic4.bmp" alt="" class="imgLittle" />
</div>
一張大圖搭配三張小圖,透過 CSS 控制大小與排版。
$(document).ready(function(){
var $warp = $("#warp");
$warp.IsRunning = false; // 動畫鎖,避免重複觸發
var seconds = 500;
$warp.children("img").click(function(){
if($warp.IsRunning){return;}
$warp.IsRunning = true;
var $imgs = $("#warp").children("img");
$imgs.eq(2).css("marginTop","63px").animate({marginTop:"0px"},{duration:seconds});
$imgs.eq(0).css({position:"absolute",opacity:"0.5"}).animate({width:"108px", height:"57px",left:"372px",top:"126px",opacity:"1"},{duration:seconds});
$imgs.eq(1).css({position:"absolute",left:"372px",top:"6px",opacity:"0.2"}).animate({width:"360px", height:"190px",left:"-9px",top:"-5px",opacity:"1"},{duration:seconds,complete:function(){
$imgs.eq(0).appendTo($("#warp"));
$imgs.eq(0).removeAttr("style").removeClass("imgBig").addClass("imgLittle");
$imgs.eq(1).removeAttr("style").removeClass("imgLittle").addClass("imgBig");
$warp.IsRunning = false;
}});
});
});
透過 IsRunning 鎖避免動畫期間重複點擊,再用 animate 讓被點的圖放大為主圖、原本的主圖縮小為小圖;動畫完成後於 complete 回呼中重排 DOM 與切換 class,確保下次點擊仍能正確運作。
.warp{width:487px; height:194px; overflow:hidden;border:solid 1px #ccc;position:relative;}
.warp img{border-width:0px;cursor:pointer;position:relative;}
.imgBig{float:left; width:360px; height:190px;padding:2px;}
.imgLittle{float:right; width:108px; height:57px;padding:6px 5px 0 10px;clear:right}