gpt4 book ai didi

javascript - 如果触发了单击事件,则阻止调用代码

转载 作者:行者123 更新时间:2023-11-28 13:14:07 25 4
gpt4 key购买 nike

我有一个非常简单的点击事件,它会触发滚动到已点击的 ID,如下所示:

$('.navigation-panel a').on('click', function () {
var id = $(this).attr('href');
$('html, body').animate({ scrollTop: $(id).offset().top - 100 }, 1000);
});

当它被触发时,它还会触发我的其他滚动事件,您可以在此处看到:

    $(window).scroll(function () {
var y = $(this).scrollTop();

menu.each(function (event) {
if (y >= $($(this).attr('href')).offset().top - 100) {
menu.not(this).removeClass('active');
$(this).addClass('active');
}
});

});

我想回答的问题是,如果点击事件已经发生,如何防止第二个脚本被执行?但是,我需要在单击事件完成后触发第二个脚本。

这些脚本必须分开,因为当用户只是滚动而不单击以导航到页面的不同部分时,第二个脚本非常重要。

最佳答案

单击时不触发事件处理程序的一种可靠方法是暂时删除事件处理程序,然后在动画结束时再次附加事件处理程序并触发它。

$(window).on('scroll', scroller);

function scroller() {
var y = $(this).scrollTop();

menu.each(function(event) {
if (y >= $($(this).attr('href')).offset().top - 100) {
menu.not(this).removeClass('active');
$(this).addClass('active');
}
});
}

$('.navigation-panel a').on('click', function() {
var id = $(this).attr('href');

$(window).off('scroll', scroller);

$('html, body').animate({
scrollTop: $(id).offset().top - 100
}, 1000, function() {
$(window).on('scroll', scroller).trigger('scroll');
});
});

关于javascript - 如果触发了单击事件,则阻止调用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40029658/

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