IE> = 8的原型Event.StopPropagation

rya*_*dlf 5 javascript

我理解为IE处理event.stopPropagation的正确方法是

if(event.stopPropagation) {
    event.stopPropagation();
} else {
    event.returnValue = false;
}
Run Code Online (Sandbox Code Playgroud)

但是有可能对Event进行原型设计,这样我每次使用stopPropagation时都不需要进行检查吗?

这个问题似乎很有帮助:IE8中的JavaScript事件原型然而我并不完全理解接受的答案以及它如何成为一个基本上可以设置和忘记的原型.

mis*_*hik 7

可能是这样的:

Event = Event || window.Event;
Event.prototype.stopPropagation = Event.prototype.stopPropagation || function() {
    this.cancelBubble = true;
}
Run Code Online (Sandbox Code Playgroud)

returnValue = false 是一个类似的preventDefault:

Event.prototype.preventDefault = Event.prototype.preventDefault || function () {
    this.returnValue = false;
}
Run Code Online (Sandbox Code Playgroud)


jfr*_*d00 6

如果你在普通的javascript中进行自己的事件处理,那么你可能已经有了一个用于设置事件处理程序的跨浏览器例程.您可以将抽象放在该函数中.这里有一个,我使用的是模仿jQuery的功能(如果事件处理函数返回false,那么这两个stopPropagation()preventDefault()触发你可以明显不过修改它,你希望它的行为:

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,你可以像这样制作一个实用函数:

function stopPropagation(e) {
    if(e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.returnValue = false;
    }    
}
Run Code Online (Sandbox Code Playgroud)

只需调用该函数,而不是在每个函数中对事件进行操作.