gpt4 book ai didi

javascript - jQuery 禁用多次点击

转载 作者:行者123 更新时间:2023-12-01 01:12:46 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的 JQuery slider ,但我在使用 .on('click') 函数时遇到了问题,如果我单击下一个或上一个按钮太快,则会超出我预期的值。

Jquery Simple Slider

var currentSlide = 1;
var $slider = $(".slides");
var slideCount = $slider.children().length;
var slideSpeed = 500;
var slideMarginLeft = -900;
var slideMarginRight = 0;

$(".prev").on('click',function(){
if(currentSlide > 1){
$slider.animate({marginLeft : slideMarginLeft + 1800} , slideSpeed, function(){
slideMarginLeft +=900;
currentSlide--;
console.log(currentSlide);
});
}
});


$(".next").on('click',function(){
if(currentSlide < 5){
$slider.animate({marginLeft : slideMarginLeft} , slideSpeed, function(){
slideMarginLeft -=900;
currentSlide++;
console.log(currentSlide);
});
}
});

最佳答案

var currentSlide = 1;
var $slider = $(".slides");
var slideCount = $slider.children().length;
var slideSpeed = 500;
var slideMarginLeft = -900;
var slideMarginRight = 0;


function previousClickCallback(animationCallback){
return function(){
if(currentSlide > 1){
$slider.animate({marginLeft : slideMarginLeft + 1800} , slideSpeed, () => {
slideMarginLeft +=900;
currentSlide--;
console.log(currentSlide);
$(".prev").once('click',previousClickCallback);
});
} else {
$(".prev").one('click',previousClickCallback);
}
}
}

function nextClickCallback(){
return function(){
if(currentSlide < 5){
$slider.animate({marginLeft : slideMarginLeft} , slideSpeed, () => {
slideMarginLeft -=900;
currentSlide++;
console.log(currentSlide);
$(".next").once('click',nextClickCallback);
});
} else {
$(".next").one('click',nextClickCallback);
}

}
}


$(".prev").one('click',previousClickCallback);
$(".next").one('click',nextClickCallback)

这应该可以,单击事件仅注册一次,一旦动画回调完成,则仅再次注册单击事件,并且将停止连续触发事件

关于javascript - jQuery 禁用多次点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55021488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com