2014-08-30 86 views
4

如何检查,如果任何引导模态当前是否打开?检查是否有任何引导模式打开

背后的原因:如果某个模式处于打开状态,我想停用某些密钥处理程序。

+0

你做了什么努力? – 2014-08-30 12:12:55

+0

我已经从下面的答案中看到了解决方案。但这不是我想要的。我想要一个通用解决方案,它适用于页面上的任何引导模式。 – Razer 2014-08-30 12:30:23

回答

1

Bootstrap模式打开时触发事件。在你的情况下,我建议绑定一个事件到show.bs.modal事件并解除你的关键处理事件。简单示例:

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

Docs:http://getbootstrap.com/javascript/#modals,向下滚动到事件。

+0

尽管我不喜欢这个问题,但这仍然是一个很好的答案,所以+1 – christopher 2014-08-30 12:15:39

+0

是的,但是对于特定的模式。我想要一个通用的解决方案。 – Razer 2014-08-30 12:28:07

+0

@Razer根据文档:“重叠模式不支持 - 一定不要打开模式,而另一个模式仍然可见。一次显示多个模式需要自定义代码。”因此,无论您是否有内置的自定义代码,或者您尝试修复的场景都不存在。如果你确实已经修复了,你可以绑定到'$(document).on('show.bs.modal','*',function(){...})' – Bjorn 2014-08-30 15:37:00

0

你可以试试这个:

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

这里借此:

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

    var element = $(this); 

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

}); 
9

如果你使用jQuery,您可以使用此:

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

香草JS解决方案:

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

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

编辑:上面的代码测试是否在任何给定时刻模态是开放的。正如在其他的答案指出,如果要禁用的事件处理程序的模式被打开的那一刻,你将不得不使用引导事件,就像这样:

// 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 
} 
0

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

return $('div.modal).hasClass('in'); // True if open, false if closed 
相关问题