最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Excluding form fields from keypress handler assigned to body - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Jun 2, 2020 at 20:28 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Oct 25, 2009 at 16:39 wfaulkwfaulk 1,7871 gold badge18 silver badges26 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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
    }
};
发布评论

评论列表(0)

  1. 暂无评论