Event capturing jQuery

后端 未结 3 2070
故里飘歌
故里飘歌 2020-11-27 18:02

I need to capture an event instead of letting it bubble. This is what I want:


   

Fro

相关标签:
3条回答
  • 2020-11-27 18:32

    More generally than @pvnarula's answer:

    var global_handler = function(name, handler) {
        var bodyEle = $("body").get(0);
        if(bodyEle.addEventListener) {
            bodyEle.addEventListener(name, handler, true);
        } else if(bodyEle.attachEvent) {
            handler = function(){
                var event = window.event;
                handler(event)
            };
            document.attachEvent("on" + name, handler)
        }
        return handler
    }
    var global_handler_off = function(name, handler) {
        var bodyEle = $("body").get(0);
        if(bodyEle.removeEventListener) {
           bodyEle.removeEventListener(name, handler, true);
        } else if(bodyEle.detachEvent) {
           document.detachEvent("on" + name, handler);
        }
    }
    

    Then to use:

    shield_handler = global_handler("click", function(ev) {
        console.log("poof")
    })
    
    // disable
    global_handler_off("click", shield_handler)
    shield_handler = null;
    
    0 讨论(0)
  • 2020-11-27 18:49

    Use event capturing instead:-

    $("body").get(0).addEventListener("click", function(){}, true);
    

    Check the last argument to "addEventListener" by default it is false and is in event bubbling mode. If set to true will work as capturing event.

    For cross browser implementation.

    var bodyEle = $("body").get(0);
    if(bodyEle.addEventListener){
       bodyEle.addEventListener("click", function(){}, true);
    }else if(bodyEle.attachEvent){
       document.attachEvent("onclick", function(){
           var event = window.event;
       });
    }
    

    IE8 and prior by default use event bubbling. So I attached the event on document instead of body, so you need to use event object to get the target object. For IE you need to be very tricky.

    0 讨论(0)
  • 2020-11-27 18:56

    I'd do it like this:

    $("body").click(function (event) {
      // Do body action
    
      var target = $(event.target);
      if (target.is($("#myDiv"))) {
        // Do div action
      }
    });
    
    0 讨论(0)
提交回复
热议问题