我创建了一个非常简单的 jQuery 内容滑块。我想把它变成一个插件,这样我就可以轻松地初始化并在初始化时指定的元素上使用它,而不必更改.each
. 这是代码:
$('.subSlider').each(function(){
var numberOfSlides = parseInt($(this).find("ul li").length);
var eachWidth = parseInt($(this).find("ul li").css("width").replace("px", ""));
var eachBorder = parseInt($(this).find("ul li").css("border-right-width").replace("px",""))+parseInt($(this).find("ul li").css("border-left-width").replace("px",""));
var eachPadding = parseInt($(this).find("ul li").css("padding-right").replace("px", ""))+parseInt($(this).find("ul li").css("padding-left").replace("px", ""));
var totalItemWidth = eachWidth+eachBorder+eachPadding;
var totalWidth = totalItemWidth*numberOfSlides;
function showHideNav(elementToMove){
if (elementToMove.css("margin-left") == "0px"){
elementToMove.parent().parent().find('.subSliderNav').not('.next').hide();
} else {
elementToMove.parent().parent().find('.subSliderNav').not('.next').show();
};
var overlap = totalWidth-elementToMove.parent().parent().width();
if (parseInt(elementToMove.css("margin-left").replace('px','')) <= -overlap){
elementToMove.parent().parent().find('.subSliderNav.next').hide();
} else {
elementToMove.parent().parent().find('.subSliderNav.next').show();
}
}
$(this).parent().prepend('<div class="subSliderNav"></div>');
$(this).parent().prepend('<div class="subSliderNav next"></div>');
$(this).parent().find('ul').width(totalWidth);
$(this).parent().on("click", ".subSliderNav", function(){
var direction = "+";
if ($(this).hasClass('next')){
direction = "-";
}
var elementToMove = $(this).parent().find('.subSlider ul');
elementToMove.animate({
"margin-left": direction+"="+totalItemWidth
}, 200, function(){
showHideNav(elementToMove);
});
});
showHideNav($(this).find('ul'));
});