单击外部菜单将其关闭



这是我的函数,

$(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将是菜单的 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();
    });

最新更新