gpt4 book ai didi

javascript - jQuery $ ('element' ).one() 来自多个位置的事件调用

转载 作者:行者123 更新时间:2023-12-02 23:18:47 26 4
gpt4 key购买 nike

我有一些模态在第二次打开时有奇怪的行为,它从我没有预料到的位置调用 .one() 事件。

第一次点击 .modal-trigger 时一切正常,与点击 .close-modal, .modal-sandbox 相同。但是当我再次点击 .modal-trigger 时,jQuery 从 modalBox.one('animationend transitionend'); 调用回调;

$(".modal-trigger").on('click', function (e) {
e.preventDefault();
let modalWindow = $($(this).attr("href"));
let modalBox = modalWindow.find('.modal-box');
let sidebarWidth = $aside.width();

$("body").css({"overflow-y": "hidden"}).addClass('blurred');

if ($(window).width() >= 992) {
modalBox.css({"margin-left": `${sidebarWidth}px`});
}

animateCSS(modalWindow, 'showing', function (element) {
element.addClass('show').removeClass('showing');
modalBox.addClass('show');
});
});

$(".close-modal, .modal-sandbox").on('click', function () {
let modalWindow = $(this).closest('.modal');
let modalBox = modalWindow.find('.modal-box');

modalBox.one('animationend transitionend', function () {
modalBox.removeAttr('style');
modalWindow.removeClass('show');
$("body").css({"overflow-y": "auto"}).removeClass('blurred');
});

modalBox.removeClass('show');
});

function animateCSS(element, animationName, callback) {
element = $(element);
element.addClass(animationName);

function handleAnimationEnd() {
element.removeClass(animationName);

if (typeof callback === 'function') callback(element);
}

element.one('animationend transitionend', handleAnimationEnd);
}

最佳答案

如果您多次调用one()...每次调用都会运行一次。

添加监听器,然后使用 off() 将其删除

 modalBox.on('animationend transitionend', function () {
modalBox.removeAttr('style');
modalWindow.removeClass('show');
$("body").css({"overflow-y": "auto"}).removeClass('blurred');
// remove listener
modalBox.off('animationend transitionend')

});

关于javascript - jQuery $ ('element' ).one() 来自多个位置的事件调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044277/

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