jQuery trigger event when click outside the element

前端 未结 11 499
无人共我
无人共我 2020-12-29 02:35
$(document).click(function(evt) {
    var target = evt.currentTarget;
    var inside = $(\".menuWraper\");
    if (target != inside) {
        alert(\"bleep\");
             


        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 03:15

    The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:

    $(".menuWrapper").click(function(e) {
      e.stopPropagation(); //stops click event from reaching document
    });
    $(document).click(function() {
      $(".menuWrapper").hide(); //click came from somewhere else
    });
    

    All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.

提交回复
热议问题