繁体   English   中英

单击外部菜单将其关闭

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM