Jquery, how: click anywhere outside of the div, the div fades out

前端 未结 6 1424
甜味超标
甜味超标 2020-12-09 06:37

In Jquery how would i make it so that if i had a div, with different elements inside of it, a select, a search input, etc, that when i click outside of the div, on the page,

6条回答
  •  爱一瞬间的悲伤
    2020-12-09 07:03

    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(); });
    

    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."

提交回复
热议问题