2014-08-30 51 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 
相關問題