1

我有一个覆盖层,我想隐藏在mousedown它外面。

这是我尝试过的,但不幸:not的是选择器没有按我预期的那样工作。

$('body:not(.overlay)').one('mousedown',function(){
        //hide overlay here
});

我也试过$('* :not(.overlay)')但同样的问题。

即使在覆盖框内单击,覆盖也会隐藏

4

3 回答 3

4
$(document).on( "mousedown.hideoverlay", function(e){
    if( $(e.target).closest(".overlay").length === 0 ) { //overlay wasn't clicked.
        //hide overlay
        $(document).off("mousedown.hideoverlay");
    }
});
于 2012-07-02T07:36:04.230 回答
2

如果您的选择器body:not(.overlay)没有 class ,则它与 body 元素匹配overlay,我假设您的意思是它的后代没有 class overlay

$('body :not(.overlay)'); //note the space - descendant selector

这种赋值的问题在于它匹配了太多的元素(特别是选定元素的父元素)。从技术上讲,即使单击任何容器div都会匹配选择器fiddled。发生这种情况是因为即使单击具有overlay类的元素也会继续传播 DOM。

我同意这里的其他建议,即,如果选择器不匹配,则适合听取所有点击并且不执行任何操作,但是阻止事件传播可能会干扰页面的其余逻辑。

我宁愿提倡一种方法,其中存在可以单击的“可叠加”项目的明确子集 - 并使用:not(.overlay)选择器过滤它们:

$('.some-generic-container-name:not(.overlay)')...
于 2012-07-02T08:05:52.890 回答
1

试试 .not() 函数:http ://api.jquery.com/not/ 。它专门从选定的组中删除元素,这可能是您遇到的问题。不必做复杂的 if 等来解决这个问题

$('*').not('.overlay').on('mousedown', function(){
    alert("here");
});

编辑

嘿,没有完全阅读问题:

$(document).on('mousedown', function(e){
   var target = $(e.target);
   if(!target.parents().hasClass('overlay') && !target.hasClass('overlay')){
      // hide stuff
   }
});

编辑:我更喜欢使用点击这里(不知道为什么):

$(document).on('click', function(e){
   var target = $(e.target);
   if(!target.parents().hasClass('overlay') && !target.hasClass('overlay')){
      // hide stuff
   }
});

在我看来它看起来更好,称我为怪...

于 2012-07-02T07:41:42.227 回答