从分配给body的按键处理程序中排除表单字段 [英] Excluding form fields from keypress handler assigned to body
问题描述
我在分配给body元素的网页上有一个按键处理程序。我真的希望它在网页的任何地方都是活跃的。或者我想。文本输入表单中的按键事件也会激活正文处理程序,这是有道理的,但我不想要。
I have a keypress handler on a web page assigned to the body element. I really do want it to be active anywhere in the web page. Or so I thought. The keypress events in textual input forms also activate the body handler, which makes sense, but which I don't want.
理想情况下,我想保留按键分配给body元素的处理程序,并以某种方式排除输入表单。有什么方法可以在输入级别停止事件并防止它传播到正文? (或者甚至是查看HTML DOM事件的正确方法?)
Ideally, I'd like to keep the keypress handler assigned to the body element and somehow exclude just the input forms. Is there any way I can stop the event at the input level and prevent it from propagating to body? (Or is that even the right way to look at HTML DOM events?)
推荐答案
简单地检查哪个元素会更容易在你的按键处理程序中触发事件并过滤掉输入元素:
It would be easier simply to check which element triggered the event in your keypress handler and filter out input elements:
document.onkeypress = function(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
if ( !/INPUT|TEXTAREA|SELECT|BUTTON/.test(target.nodeName) ) {
// Do stuff
}
};
这篇关于从分配给body的按键处理程序中排除表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!