我正在为我当前的应用程序几乎所有事件调用e.stopPropagation()
。有没有办法只停止每个事件的传播而不必在每个函数体的开头显式调用该方法?
答案 0 :(得分:11)
您可以绑定所有事件(删除您不需要的事件):
$('*').bind('blur change click dblclick error focus focusin focusout hover keydown keypress keyup load mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup resize scroll select submit', function(event){
event.stopPropagation();
});
查看可能发生的事件
答案 1 :(得分:5)
不能全局声明
event.stopPropagation()
方法停止将事件冒泡到父元素,从而阻止执行任何父事件处理程序。
例如,如果在DIV或FORM中附加了点击方法的链接也附加了点击方法,则会阻止点击DIV或FORM点击方法。
答案 2 :(得分:2)
以Alex的回应为基础,在vanilla JS中以及更多事件(我能找到的所有键盘和点击事件):
/**
* Disable all user events on the page
*
* @returns {function()} a function to cancel the disabling
*/
const disableAllUserEvents = () => {
const events = ["click", "contextmenu", "dblclick", "mousedown", "mouseenter", "mouseleave", "mousemove",
"mouseover", "mouseout", "mouseup", "keydown", "keypress", "keyup", "blur", "change", "focus", "focusin",
"focusout", "input", "invalid", "reset", "search", "select", "submit", "drag", "dragend", "dragenter",
"dragleave", "dragover", "dragstart", "drop", "copy", "cut", "paste", "mousewheel", "wheel", "touchcancel",
"touchend", "touchmove", "touchstart"];
const handler = event => {
event.stopPropagation();
event.preventDefault();
return false;
};
for (let i = 0, l = events.length; i < l; i++) {
document.addEventListener(events[i], handler, true);
}
return () => {
for (let i = 0, l = events.length; i < l; i++) {
document.removeEventListener(events[i], handler, true);
}
};
};
编辑:只知道这不是一个安全的解决方案,因为可以检索和取消这些事件:Use Chrome's webkit inspector to remove an event listener
答案 3 :(得分:-2)
试试这个。 需要jQuery 。
$('*').on('click', function(e){
e.stopPropagation();
});