如何阻止所有事件的传播

时间:2013-07-15 00:05:25

标签: javascript dom javascript-events stoppropagation

我想知道当它们到达某个元素时如何阻止所有类型事件的传播。

我想过

function stop(e){
    e.stopPropagation();
}
function stopEvents(el){
    var events = ['click', 'mousemove', ...];
    for(var i=0; i<events.length; ++i){
        el.addEventListener(events[i], stop, false);
    }
}

有更聪明的方法吗?

似乎我的代码有效,但我希望代码不需要列出所有可能的事件。

  

因为如果我写了一个其他人可以使用的GreaseMonkey模块   向页面添加内容,我不希望在其中生成事件   触发页面事件监听器的内容(假设它们不使用   捕获)。实际上我用iframe解决了它,但问题仍然存在   用于学术目的

2 个答案:

答案 0 :(得分:5)

function stop(e){
    e.stopPropagation();
}
function stopEvents(el){
    for(var key in window) {
        if (key.indexOf("on") == 0) {
            el.addEventListener(key.substr(2), stop, false);
        }
    }
}

这就是你如何获得所有活动的方法。

这可能会导致一些问题。例如,如果您将另一个键添加到以window开头的on对象中,则该键也将被视为"event"

您还必须考虑window对象很大。

我会使用你的代码。完整的事件列表将是:

谷歌浏览器

["deviceorientation", "transitionend", "webkittransitionend", "webkitanimationstart", "webkitanimationiteration", "webkitanimationend", "search", "reset", "waiting", "volumechange", "unload", "timeupdate", "suspend", "submit", "storage", "stalled", "select", "seeking", "seeked", "scroll", "resize", "ratechange", "progress", "popstate", "playing", "play", "pause", "pageshow", "pagehide", "online", "offline", "mousewheel", "mouseup", "mouseover", "mouseout", "mousemove", "mousedown", "message", "loadstart", "loadedmetadata", "loadeddata", "load", "keyup", "keypress", "keydown", "invalid", "input", "hashchange", "focus", "error", "ended", "emptied", "durationchange", "drop", "dragstart", "dragover", "dragleave", "dragenter", "dragend", "drag", "dblclick", "contextmenu", "click", "change", "canplaythrough", "canplay", "blur", "beforeunload", "abort"]

火狐

["SearchSubmit", "mouseenter", "mouseleave", "afterprint", "beforeprint", "beforeunload", "hashchange", "message", "offline", "online", "popstate", "pagehide", "pageshow", "resize", "unload", "devicemotion", "deviceorientation", "deviceproximity", "userproximity", "devicelight", "abort", "blur", "canplay", "canplaythrough", "change", "click", "contextmenu", "dblclick", "drag", "dragend", "dragenter", "dragleave", "dragover", "dragstart", "drop", "durationchange", "emptied", "ended", "error", "focus", "input", "invalid", "keydown", "keypress", "keyup", "load", "loadeddata", "loadedmetadata", "loadstart", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "mozfullscreenchange", "mozfullscreenerror", "mozpointerlockchange", "mozpointerlockerror", "pause", "play", "playing", "progress", "ratechange", "reset", "scroll", "seeked", "seeking", "select", "show", "stalled", "submit", "suspend", "timeupdate", "volumechange", "waiting", "wheel", "copy", "cut", "paste", "beforescriptexecute", "afterscriptexecute"]

答案 1 :(得分:1)

残疾人专区有可能css吗?

pointer-events : none;