Prototype Event.StopPropagation for IE >= 8

后端 未结 3 1856
遇见更好的自我
遇见更好的自我 2021-02-10 04:07

I understand the proper way to handle event.stopPropagation for IE is

if(event.stopPropagation) {
    event.stopPropagation();
} else {
    event.returnValue = f         


        
相关标签:
3条回答
  • 2021-02-10 04:12

    If you're doing your own event handling in plain javascript, then you probably already have a cross browser routine for setting event handlers. You can put the abstraction in that function. Here's one that I use that mimics the jQuery functionality (if the event handler returns false, then both stopPropagation() and preventDefault() are triggered. You can obviously modify it however you want it to behave:

    // refined add event cross browser
    function addEvent(elem, event, fn) {
        // allow the passing of an element id string instead of the DOM elem
        if (typeof elem === "string") {
            elem = document.getElementById(elem);
        }
    
        function listenHandler(e) {
            var ret = fn.apply(this, arguments);
            if (ret === false) {
                e.stopPropagation();
                e.preventDefault();
            }
            return(ret);
        }
    
        function attachHandler() {
            // normalize the target of the event
            window.event.target = window.event.srcElement;
            // make sure the event is passed to the fn also so that works the same too
            // set the this pointer same as addEventListener when fn is called
            var ret = fn.call(elem, window.event);   
            // support an optional return false to be cancel propagation and prevent default handling
            // like jQuery does
            if (ret === false) {
                window.event.returnValue = false;
                window.event.cancelBubble = true;
            }
            return(ret);
        }
    
        if (elem.addEventListener) {
            elem.addEventListener(event, listenHandler, false);
        } else {
            elem.attachEvent("on" + event, attachHandler);
        }
    }
    

    Or, you can just make a utility function like this:

    function stopPropagation(e) {
        if(e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.returnValue = false;
        }    
    }
    

    And just call that function instead of operating on the event in each function.

    0 讨论(0)
  • 2021-02-10 04:12

    Probably this:

    Event = Event || window.Event;
    Event.prototype.stopPropagation = Event.prototype.stopPropagation || function() {
        this.cancelBubble = true;
    }
    

    returnValue = false is an analogue for preventDefault:

    Event.prototype.preventDefault = Event.prototype.preventDefault || function () {
        this.returnValue = false;
    }
    
    0 讨论(0)
  • 2021-02-10 04:37

    We can use this alone: event.cancelBubble = true.

    Tested working in all browsers.

    0 讨论(0)
提交回复
热议问题