我刚刚用 jQuery 做了一个幻灯片,查看了“下一张幻灯片”和“上一张幻灯片”按钮的代码,我意识到它们几乎是一样的,除了几个功能发生了变化。
我认为这可以被重构以提高效率,但我不确定如何。
有人可以告诉我怎么做吗?
//UI Binding
$nextbutton.on("click", function(){
//Blocking control
if (slideshowBlocked) return;
slideshowBlocked = true;
//Get active slide
var $active = $slides.filter(".active");
//Get new Slied
var $newSlide = $active.next(".slide");
if (!$newSlide.length){
$newSlide = $slides.first();
}
//Prepare new slide beneath the active
$newSlide.css({
"z-index": 5,
"display": "block"
});
//Fade out the active
$active.fadeOut(function(){
//Update states and CSS properties
$(this).removeClass("active");
$newSlide.addClass("active").css( "z-index", 10);;
//Unblock slideshow
slideshowBlocked = false;
});
});
$prevbutton.on("click", function(){
//Blocking control
if (slideshowBlocked) return;
slideshowBlocked = true;
//Get active slide
var $active = $slides.filter(".active");
//Get new Slied
var $newSlide = $active.prev(".slide");
if (!$newSlide.length){
$newSlide = $slides.last();
}
//Prepare new slide beneath the active
$newSlide.css({
"z-index": 5,
"display": "block"
});
//Fade out the active
$active.fadeOut(function(){
//Update states and CSS properties
$(this).removeClass("active");
$newSlide.addClass("active").css( "z-index", 10);;
//Unblock slideshow
slideshowBlocked = false;
});
});