我有一個具有多個滑塊(從http://www.switchonthecode.com/tutorials/using-jquery-slider-to-scroll-a-div)一個頁面,因爲他們每個人都是不同的div我只是重複的代碼,並把它改爲獨特的類,把這個代碼:多個jQuery滑塊移動每個div在同一頁面,任何方式來簡化代碼?
$(document).ready(function(){
$(".slider1").slider({
animate: true,
handle: ".handle1",
change: handleSliderChange1,
slide: handleSliderSlide1
});
$(".slider2").slider({
animate: true,
handle: ".handle2",
change: handleSliderChange2,
slide: handleSliderSlide2
});
$(".slider3").slider({
animate: true,
handle: ".handle3",
change: handleSliderChange3,
slide: handleSliderSlide3
});
});
function handleSliderChange1(e, ui)
{
var maxScroll = $(".gal1").attr("scrollWidth") - $(".gal1").width();
$(".gal1").animate({scrollLeft: ui.value * (maxScroll/100) }, 1000);
}
function handleSliderSlide1(e, ui)
{
var maxScroll = $(".gal1").attr("scrollWidth") - $(".gal1").width();
$(".gal1").attr({scrollLeft: ui.value * (maxScroll/100) });
}
function handleSliderChange2(e, ui)
{
var maxScroll = $(".gal2").attr("scrollWidth") - $(".gal2").width();
$(".gal2").animate({scrollLeft: ui.value * (maxScroll/100) }, 1000);
}
function handleSliderSlide2(e, ui)
{
var maxScroll = $(".gal2").attr("scrollWidth") - $(".gal2").width();
$(".gal2").attr({scrollLeft: ui.value * (maxScroll/100) });
}
function handleSliderChange3(e, ui)
{
var maxScroll = $(".gal3").attr("scrollWidth") - $(".gal3").width();
$(".gal3").animate({scrollLeft: ui.value * (maxScroll/100) }, 1000);
}
function handleSliderSlide3(e, ui)
{
var maxScroll = $(".gal3").attr("scrollWidth") - $(".gal3").width();
$(".gal3").attr({scrollLeft: ui.value * (maxScroll/100) });
}
雖然這工作得也很好,我有大約7這些幻燈片(只有3上面顯示),我覺得有點重複基本上相同的代碼...
有沒有辦法簡化這段代碼?
真棒,這正是我尋找。雖然在這種情況下,滑塊必須在滑動內容之前......因爲我可以用css處理它,所以它不成問題:D 非常感謝! :D – 2011-04-04 07:59:41
如果您需要以不同的順序排列滑塊和內容,則可以更改jQuery正在尋找的「兄弟」。如果滑塊和內容是兄弟,也許使用[prev()](http://api.jquery.com/prev/)而不是next()。 – andyb 2011-04-04 08:45:57