javascript - 在javascript中捕获网页上的键盘输入
问题描述
我想使用 javascript 控制网页的输入焦点。实际上,我正在开发一个在网页上加载内容脚本的 webExtension。该网页预先设计为自动收集键盘输入。但是,我希望我的脚本在某些情况下通过我附加到页面的 inputBox 接收键盘输入。但是所有键盘输入似乎都进入了页面的原始输入框。这是我目前的草稿
//TODO: steal focus to myInputBox
//while keydown is shiftkey, steal and retain the focus on myInputBox
//subsequently collect keyboard inputs
document.addEventListener("keydown", function(e){
if (e.shiftKey)
{
e.preventDefault(); //prevent shiftkey from modifying the input, I guess. Still learning though
document.getElementById("myInputBox").focus(); //focus myInputBox subsequently accepting keyboard input from now on...
}
});
但键盘输入仍然进入原始输入框
///////很好,我找到了解决办法。这是我的修复,可能对其他人有帮助
document.addEventListener("keyup",function(){
if (e.key == "A" || e.key == "a")
{
var origInput = document.getElementById("origInputID");
origInput.disabled = !origInput.disabled;//use "!" to toggle current
//state
if (origInput.disabled === true)
{
document.getElementById("myInput").focus();
}
}});
解决方案
你的例子对我有用。我对其进行了更新,因此当班次下降时它在备用框中输入,然后在班次上升时在原始框中输入。不确定这是不是你想要的...
要在 shift 键按下时获得未移动的字符,您可能必须跟踪 shift 键的状态,然后打开键码。我认为您不能阻止 shift 键影响生成的charcode。防止默认不会导致生成不同的字符码,键码将是恒定的。
字符代码 - 代表 ASCII 字符的数字
键码 - 代表键盘上实际键的数字
let editMode = false
document.addEventListener("keydown", function(e) {
if (e.shiftKey && !editMode) {
//e.preventDefault();
editMode = true
document.getElementById("myInputBox").focus();
}
})
document.getElementById("myInputBox").addEventListener("keyup", function(e) {
if (editMode && !e.shiftKey) {
//e.preventDefault();
editMode = false
document.getElementById("other").focus();
}
})
document.getElementById("other").focus();
Start with focus here, then press and hold shift
<input id='other'></input>
<hr />
Target
<input id='myInputBox'></input>
推荐阅读
- spring - http 404 错误源服务器没有找到目标资源的当前表示或不愿意透露存在的表示
- recursion - makefile递归所有子系统总是最新的
- python - 将大型 python 文件拆分为较小的文件
- c# - EF Core 修改实体状态的行为如何?
- ios - Alamofire POST 请求,正文中有一个简单的字符串作为参数,标头仍然显示缺少参数值
- cesium - Cesium:我可以用图像覆盖地形,然后在其上添加slopeRamp 材质吗?
- angular - 材料表格的材料表(使用材料滑块)不起作用
- angular - 角度材料步进器在每次点击时动态添加新的步进项目
- react-native - 尝试安装 react-native-google-place-picker
- android - 融合位置提供程序 setSmallestDisplacement 在特定运动中不起作用