jQuery trigger event when click outside the element

前端 未结 11 544
无人共我
无人共我 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:19

    This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.

    function tog_alerts(){
       if($('#Element').css('display') == 'none'){
           $('#Element').show();
           setTimeout(function () {
               document.body.addEventListener('click', Close_Alerts, false);
           }, 500);
       }
    }
    
    function Close_Alerts(e){
       var current = e.target;
       var check = 0;
       while (current.parentNode){
          current = current.parentNode
          if(current.id == 'Element'){
             check = 1;
          }
       }
       if(check == 0){
          document.body.removeEventListener('click', Close_Alerts, false);
          $('#Element').hide();         
       }
    }
    

提交回复
热议问题