jQuery trigger event when click outside the element

前端 未结 11 500
无人共我
无人共我 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 02:57

    if you have child elements like dropdown menus

    $('html').click(function(e) {
      //if clicked element is not your element and parents aren't your div
      if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
        //do stuff
      }
    });
    
    0 讨论(0)
  • 2020-12-29 03:08
    $(document).click((e) => {
      if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
      } else {
        this.onClose();
      }
    }); 
    
    0 讨论(0)
  • 2020-12-29 03:09

    I know that the question has been answered, but I hope my solution helps other people.

    stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.

    My solution:

    $(document).click(function(e) {
        if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
            $(e.target).closest("#div-exception").attr("id") != "div-exception") {
            alert("Clicked outside!");
        }
    });
    

    http://jsfiddle.net/NLDu3/

    0 讨论(0)
  • 2020-12-29 03:09

    try this one

        $(document).click(function(event) {
    
            if(event.target.id === 'xxx' )
                return false;
            else {
                  // do some this here
            }
    
        });
    
    0 讨论(0)
  • 2020-12-29 03:10

    I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...

    0 讨论(0)
  • 2020-12-29 03:10
        var visibleNotification = false;
    
      function open_notification() {
            if (visibleNotification == false) {
                $('.notification-panel').css('visibility', 'visible');
                visibleNotification = true;
            } else {
                $('.notification-panel').css('visibility', 'hidden');
                visibleNotification = false;
            }
        }
    
        $(document).click(function (evt) {
            var target = evt.target.className;
            if(target!="fa fa-bell-o bell-notification")
            {
                var inside = $(".fa fa-bell-o bell-notification");
                if ($.trim(target) != '') {
                    if ($("." + target) != inside) {
                        if (visibleNotification == true) {
                            $('.notification-panel').css('visibility', 'hidden');
                            visibleNotification = false;
                        }
                    }
                }
            }
        });
    
    0 讨论(0)
提交回复
热议问题