如何在 javascript 中使用关键事件,使其不传播?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4470417/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I consume a key event in javascript, so that it doesn't propagate?
提问by Tom Brito
How do I consume a key event in javascript, so that it doesn't propagate?
如何在 javascript 中使用关键事件,使其不传播?
采纳答案by Douglas
Try preventDefaultand/or stopPropagation.
回答by Tim Down
If you don't want the event to propagate and you're not using jQuery (or another library that wraps native browser events), you need to use the event's stopPropagation()method in most browsers and its cancelBubbleproperty in IE. Don't bother with return falseor preventDefault(): those only affect whether the native browser action happens for the event and have nothing to do with propagation.
如果您不希望事件传播并且您没有使用 jQuery(或其他包装本机浏览器事件的库),则需要stopPropagation()在大多数浏览器中使用该事件的方法,并cancelBubble在 IE 中使用它的属性。不要理会return falseor preventDefault():那些只影响本地浏览器操作是否为事件发生,与传播无关。
For example:
例如:
document.onkeypress = function(evt) {
    evt = evt || window.event;
    if (typeof evt.stopPropagation != "undefined") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
};

