javascript - 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.
解决方案
为您的文本部分使用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)
推荐阅读
- excel-formula - 从excel中的多个工作表返回重复值的位置
- xcode - 无法在 Visual Studio for Mac 上为 CocoaApp (Xamarin.Forms) 构建安装程序
- excel - VBa代码打开关闭的文件并复制列工作但什么也没做
- javascript - Yajra 数据表修改后的每列搜索
- javascript - FirebaseError:预期类型'Tc',但它是:一个对象
- magento2 - Magento 2 - 从 M1 迁移后保存分组产品时出现问题
- ios - 没有导航栏的导航视图控制器
- kafka-consumer-api - 从主题中 kafka 分区的特定偏移量启动 flink 流应用程序
- c# - EWS SaveHttpResponseHeaders 异常 - 已添加具有相同密钥的项目
- python - 每 10 分钟运行一次并生成 csv 文件的 python 脚本