首页 > 解决方案 > 在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();
    }
}});

标签: javascriptfirefox-addon-webextensions

解决方案


你的例子对我有用。我对其进行了更新,因此当班次下降时它在备用框中输入,然后在班次上升时在原始框中输入。不确定这是不是你想要的...

要在 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>


推荐阅读