首页 > 解决方案 > How to use Javascript to determine where a user is typing on webpage and react accordingly

问题描述

I am new to javascript, and am writing a simple bookmarklet for a webpage that has a text input section. Basically what I need is a way to execute the following-


if ( ! (text_section).onkeydown ) { 

     do whatever

}

I need to ignore key-events when the user is typing inside an input field but otherwise trigger key-events for the entire page whenever the user presses a key. I do know that onkeydown is an event listener/handler I'm just trying to explain what I need to do more accurately.

标签: javascriptbookmarklet

解决方案


为您的文本部分使用id,例如“myTextSection”。将addEventListener应用于整个文档。如果目标是除文本字段之外的任何其他内容,请执行以下操作:

document.addEventListener("keydown", (event) => {
    if(event.target !== document.getElementById("myTextSection")){
         //do whatever;
    }
});

请注意,这种行为可能会让用户感到恼火,因为用户使用键盘(例如制表符空格键)在您的页面中导航。因此,您可能需要添加另一个 if 语句来检查event.keyCode是否为字母数字。在这种情况下,keyCode 在范围内

  • [47-58](对于 0-9),
  • [64-91](对于 AZ)或
  • [96-123](用于 az)

推荐阅读