2

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

我曾想过

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 解决了它,但问题仍然用于学术目的

4

2 回答 2

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);
        }
    }
}

This is how you could get all of the events.

This could cause some issue though. For example, if you add another key into the window object that starts with on, it will also be considered an "event".

You also have to consider that the window object is large.

I would just use your code. The full list of events would be:

Google Chrome

["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"]

FireFox

["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"]
于 2013-07-15T00:11:16.080 回答
1

css残疾人区有机会吗?

pointer-events : none;
于 2013-07-15T00:38:55.873 回答