[英]Click outside menu to close it
這是我的功能,
$(document).ready(function () {
$('.a').click(function () {
var here = $(this).next('.b');
if (here.is(":visible")) {
here.hide();
} else {
here.show();
}
return false;
});
});
因此,每當我單擊該按鈕時,它都會在同一網頁上打開一個小標簽,而每當我再次單擊它時,它就會關閉它。 但是一旦我打開標簽,我就無法通過點擊網頁上除標簽之外的某個地方來關閉它。 我必須再次單擊該按鈕才能關閉它。
如何僅通過單擊網頁上的某處也單擊按鈕來關閉選項卡?
我最終幾乎在每個項目中都搜索了這個,所以我制作了這個插件:
jQuery.fn.clickOutside = function(callback){
var $me = this;
$(document).mouseup(function(e) {
if ( !$me.is(e.target) && $me.has(e.target).length === 0 ) {
callback.apply($me);
}
});
};
它需要一個回調函數並傳遞您的原始選擇器,因此您可以執行以下操作:
$('[selector]').clickOutside(function(){
$(this).removeClass('active'); // or `$(this).hide()`, if you must
});
漂亮,可鏈接,優雅的代碼。
單擊文檔時,最接近的有助於檢查選項卡是否已被單擊:
$(document).click(function (e) {
if($('.b').is(':visible')&&!$(e.target).closest('.b').length){
$('.b').hide();
}
});
你想檢查身體上的點擊:
$("body").click(function(e) {
if(e.target.id !== 'menu'){
$("#menu").hide();
}
});
menu
將是menu
的 id。
如果單擊主體並且單擊的 div 的 id 與菜單的 id 不相等,則它會關閉。
檢查這個實現
jQuery(document).ready(function() { $(document).on('click','body, #btn',function(ev){ ev.stopPropagation() if(ev.target.id== "btn"){ if($('#modal').is(':visible')) { $('#modal').fadeOut(); } else{ $('#modal').fadeIn(); } } else { $('#modal').fadeOut(); } }); });
html, body { height: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn"> Click Me! </button> <div id="modal" style="background-color:red;display:none;"> BLA BLA BLA </div>
要檢查被點擊的元素是否在給定的容器(即菜單)之外,我們可以簡單地檢查事件目標是否是容器的子元素。 使用 JQuery -
$('body').click(function(e) {
if ( 0 === $(e.target).parents('#container-id').length ) {
/// clicked outside -> do action
}
})
您必須向父元素添加一個單擊偵聽器,如下所示:
$('.parent-div').click(function() {
//Hide the menus if visible
});
也因為單擊事件從子元素冒泡到父元素,您可以排除子元素上的單擊以冒泡並計為父單擊。 你可以像下面這樣實現:
//disable click event on child element
$('.child-div').click(function(event){
event.stopPropagation();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.