圖片左右無縫滾動是首頁輪播、產品展示中常見的效果。本文分享一個以 jQuery 實作的插件,透過點擊左右按鈕,讓圖片列表以無縫的方式循環滾動。
(function($){
$.fn.extend({
"slidelf":function(value){
value = $.extend({
"prev":"",
"next":"",
"speed":""
},value)
var dom_this = $(this).get(0); //將jquery對象轉換成DOM對象
var marginl = parseInt($("ul li:first",this).css("margin-left")); //每個圖片margin的數值
var movew = $("ul li:first",this).outerWidth()+marginl; //需要滑動的數值
//左邊的動畫
function leftani(){
$("ul li:first",dom_this).animate({"margin-left":-movew},value.speed,function(){
$(this).css("margin-left",marginl).appendTo($("ul",dom_this));
});
}
//右邊的動畫
function rightani(){
$("ul li:last",dom_this).prependTo($("ul",dom_this));
$("ul li:first",dom_this).css("margin-left",-movew).animate({"margin-left":marginl},value.speed);
}
//點擊左邊
$("."+value.prev).click(function(){
if(!$("ul li:first",dom_this).is(":animated")){
leftani();
}
});
//點擊右邊
$("."+value.next).click(function(){
if(!$("ul li:first",dom_this).is(":animated")){
rightani();
}
})
}
});
})(jQuery)
點擊左邊(向左滾動):
點擊右邊(向右滾動):
需要特別注意的是程式碼中的 IF 判斷——它是為了防止連續點擊「左」或「右」按鈕而出現的 BUG。這個判斷的意思是:只有當 LI 不處於動畫狀態時,才執行移動函數;只要處於動畫狀態,點擊時便不做任何反應,從而保證滾動動畫的連貫與穩定。