且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery,方法:单击div之外的任何位置,div消失

更新时间:2023-02-19 21:01:22

Code Duck的答案不完整,因为如果您单击DIV本身,则需要使其 not 淡出(仅限外部). ).因此,假设您应该淡出的DIV的ID为菜单".

Code Duck's answer is incomplete, because you'd need to have it not fade out if you click the DIV itself (only outside). So say your DIV that's supposed to fade out has an ID of "menu".

jQuery("#menu").click(function(){ return false; });
jQuery(document).one("click", function() { jQuery("#menu").fadeOut(); });

使用 一个 比绑定/取消绑定更简洁.另外,如果您使用 one ,则这里实际上不需要命名空间事件,因为不需要显式取消绑定文档上的特定单击处理程序.

The use of one is more concise than the bind/unbind. Also namespaced events aren't really needed here if you use one because there's no need to explicitly unbind a particular click handler on document.

返回假 只是说停止将事件一直冒泡到文档中."

The return false is just saying "stop bubbling this event up to the document."