2010-09-07 42 views
1

这是我正在做的事情。抓住一只老鼠单击一个元素旁边的事件

我在链接显示对话框中,单击后 CSS

#toshow { display:none; } 

HTML

<a href="#" id="mylink" >Link</a> 
<div id="toshow">Here is my content</div> 

jQuery的

$(document).ready(function() { 
    $("#mylink").click(function() { 
     $("#toshow").show(); 
    }); 
}); 

现在我想捕捉一个事件,用户单击鼠标,如果用户点击的部分不是链接或分区,则分区应该再次隐藏。

如何做到这一点?

回答

2
$(document.body).click(function(e){ 
    var $box = $('#mylink'); 
    if(e.target.id !== 'mylink' && !$.contains($box[0], e.target)) 
     $("#toshow").hide(); 
}); 

您需要检查哪些冒泡到document.body的单击事件。在那个事件处理程序中,您查找event target id,并将其与您所做的元素NOT想要包括的元素进行比较,以及所有排除元素的子元素。

@Starx :(在评论中提问) $.contains()检查DOM node是否包含您指定的另一个节点。所以

!$.contains($box[0], e.target) 

手段,if e.target does NOT contain the node $box[0]
看到http://api.jquery.com/jQuery.contains/

+1

不是'$ box.hide()'出于任何原因? – sje397 2010-09-07 07:22:59

+0

@ sje397 - 绝对地,删除该框会阻止#mylink在下次点击时再次点击该框。 – Fenton 2010-09-07 07:28:47

+0

@ sje397,@索尼:ups我的坏。 – jAndy 2010-09-07 07:31:56

0

绑定的点击甚至(或鼠标按下事件)的文档对象:

$(document).bind('click', hideToShow()); 
1

首先,你应该是位亲切的不通过编程方式隐藏内容的JavaScript谁,而不是通过CSS的用户。您也可以使相同的链接隐藏内容。

$(document).ready(function() { 
    $("#toshow").hide(); 

    $("#mylink").click(function() { 
     $("#toshow").toggle(); 
    }); 
}); 

如果您想按照您的建议“点击离焦”,则需要执行此操作。

$(document).ready(function() { 
    $("#toshow").hide(); 

    $("#mylink").click(function() { 
     $("#toshow").show(); 
    }); 

    $("body").click(function() { 
     $("#toshow").hide(); 
    }); 

    $("#toshow").click(function (e) { 
     e.stopPropagation(); 
     return false; 
    }); 
}); 

最后一位,在这里我们点击处理程序添加到#toshow旨在阻止点击事件的传播到文档的身体当你点击该元素上。

+0

清晰可读。我喜欢。 +1 – ljubomir 2010-09-07 07:32:50

0

您应该绑定文档对象上的单击事件侦听器,并且每次触发事件时都必须检查事件目标元素(发起事件的DOM元素)。你可以这样说:


$(document).ready(function() { 
    $(document).click(function(event) { 
     var $target = $(event.target); 
     if (!$target.is('#mylink') && !$('#toshow').contains($target) && $('#toshow').is(':visible')) { // check if user clicled not on #mylink and outside of #toshow 
      $("#toshow").hide(); 
     } else if ($target.is('#mylink') && !$('#toshow').is(':visible')) { // check if user clicked #mylink and #toshow is hidden 
      $("#toshow").show(); 
     } 
    }); 
}); 
0
$('input').on('blur', function() { 
    //do something 
}); 

你可以把你的元素ID而不是“输入”。

相关问题