Bootstrap 检查是否打开了任何引导模式

yks3o0rb  于 2022-12-08  发布在  Bootstrap
关注(0)|答案(8)|浏览(174)

如何检查任何 Bootstrap 模态当前是否打开?
背后的原因:我想停用某个keyhandler,如果一个modal是打开的。

oogrdqng

oogrdqng1#

如果您正在使用jquery,则可以使用以下命令:

function isABootstrapModalOpen() {
    return $('.modal.in').length > 0;
}

香草JS溶液:

function isABootstrapModalOpen() {    
    return document.querySelectorAll('.modal.in').length > 0;
}

此解决方案适用于任何模态,而不仅仅是特定模态。

Edit:上面的代码测试在任何给定的时刻,模态是否打开。如其他答案所示,如果你想在模态打开时禁用事件处理程序,你必须使用 Bootstrap 事件,如下所示:

// when any modal is opening
$('.modal').on('show.bs.modal', function (e) {
  // disable your handler
})

// when any modal is closing
$('.modal').on('hide.bs.modal', function (e) {
  // enable your handler
})

您还可以在事件处理程序中使用isABootstrapModalOpen,以测试是否必须执行处理程序的代码(这样就不必在每次打开/关闭模态时启用/禁用处理程序)。

function eventHandler(e) {
  // if a modal is open
  if(isABootstrapModalOpen()) {
    // prevent the event default action
    e.preventDefault();
    // and exit the function now
    return;
  }

  // if a modal is not open
  // proceed to the rest of the handler's code 
}
okxuctiv

okxuctiv2#

Bootstrap模态在打开时触发事件。在您的情况下,我建议将一个事件绑定到show.bs.modal事件,并取消绑定您的键处理程序事件。简单的例子:

$('#myModal').on('show.bs.modal', function (e) {
    // yadda yadda .unbind()
})

文件:请向下卷动至“事件”。

wswtfjt7

wswtfjt73#

"拿着这个"

$(document).find('.modal').each(function(e) {

    var element = $(this);

    if ( (element.data('bs.modal') || {isShown: false}).isShown ) {
      console.log('a modal is open');
    }

});
eblbsuwk

eblbsuwk4#

我的解决方案是使用jQueries的hasClass方法。

return $('div.modal').hasClass('in'); // True if open, false if closed
v2g6jxz6

v2g6jxz65#

您可以尝试:

alert($('#myModal').hasClass('in'));
nimxete2

nimxete26#

对于Bootstrap 4,如果打开,则模态具有类“show”
因此要检查是否有模态打开:

if ($('body').find('.modal.show').length) {
    // Do something
}

我目前使用的是堆叠式模态(multiple open),问题是,如果你对单个模态执行.modal('hide'),Bootstrap会从body元素中删除class .modal-body。然后模态不再滚动,所以我不得不这样做:

$(document)
    .on('hidden.bs.modal', '.modal', function() {
        /**
         * Check if there are still modals open
         * Body still needs class modal-open
         */
        if($('body').find('.modal.show').length) {
            $('body').addClass('modal-open');
        }
    })
;
628mspwn

628mspwn7#

虽然不是这个直接问题的答案,但它是相关的。下面是如何检查是否在Bootstrap 4模态中:if (window.parent.jQuery('.modal-content').length > 0) { // in a modal }

1hdlvixo

1hdlvixo8#

您可以使用此选项:

$('#mymodal').on('shown.bs.modal', function (e) {
    console.log("Modal is open");
})

相关问题