Excluding form fields from keypress handler assigned to body

陌路散爱 提交于 2019-12-04 04:27:21

问题


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.

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?)


回答1:


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


来源:https://stackoverflow.com/questions/1621346/excluding-form-fields-from-keypress-handler-assigned-to-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!