iPad 蓝牙键盘 returns 使用 onKeyUp 的任意键的键码为 0

iPad Bluetooth keyboard returns keycode of 0 for any key with onKeyUp

一些客户在使用他们的 iPad 蓝牙键盘向我们的一个内部站点输入文本时报告了问题。在使用桌面或 iPad 屏幕键盘时,主要是在某个输入上按 enter 可以正常工作,但在使用连接到 iPad 的蓝牙键盘时则不行。

经调查,当连接到 iPad 上的蓝牙键盘时,对 onKeyUp returns 0 的任何输入似乎都是键码。该演示工作正常,但是当使用屏幕键盘时它不起作用,因为键码返回 0。I created this jsFiddle to demonstrate. 它在 Chrome 和 Safari 上针对 iPad 进行了测试,结果相同在 onKeyPress 下工作正常,但在 onKeyUp.

下只返回 0

$('#inputKeyUp').keyup(function (event){
 $("#outputKeyUp").text("Key Up Key: " + event.which);
});

$('#inputKeyPress').keypress(function (event){
 $("#outputKeyPress").text("Key Press Key: " + event.which);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="inputKeyUp">keyup</textarea>
<div id="outputKeyUp">Key Up Key:</div>
<b/>
<textarea id="inputKeyPress">keypress</textarea>
<div id="outputKeyPress">Key Press Key:</div>

编辑:刚刚向 Apple 报告了该错误。我们会看看是否有结果。

测试研究

我刚才对此做了一些测试,发现在 iOS Safari 上使用蓝牙键盘时,在 keyUp 事件中,唯一能提供任何类型适当反馈的键属性 e.keye.charCodee.keyCodee.which 是以下键:

  • 逃脱
  • 向上箭头
  • 向左箭头
  • 向右箭头
  • 向下箭头

所有其他键 return 以下:

{
    key: "Dead",
    charCode: 0,
    keyCode: 0,
    which: 0
}

这些特殊键(转义键和箭头键)只是 return 根据语法 UIKeyInput{PascalCasedKeyName}:

e.key 属性 上的不同值
  • UIKeyInputEscape
  • UIKeyInputUpArrow
  • UIKeyInputLeftArrow
  • UIKeyInputRightArrow
  • UIKeyInputDownArrow

总结

在 iOS 上,根据我的快速研究,您可以在 keyUp 事件中识别的唯一键是 Escape 和四个 Arrow keys,通过匹配他们的名字在 e.key 属性 上。这些值也出现在 keyDown 事件中。

如果您仍然需要等到 keyUp 事件为您的应用程序触发,并且您需要匹配这些特殊键以外的键,我能想到的唯一解决方案是使用 keyDown 事件捕获密钥,然后监听 keyUp 事件 inside that keyDown event like so:

el.addEventListener("keydown", e => {
    if (e.which === 13) // Enter key, or which ever key code you'd like
        el.addEventListener("keyup", function keyUp(e) {
            el.removeEventListener("keyup", keyUp, false) // Memory clean-up

            // Your code here
        }, false)
}, false)

此外

快速搜索 "UIKeyInput" 后,我发现 UIKeyInput 是 "a set of methods a subclass of UIResponder uses to implement simple text entry"。 (Apple's Developer Documentation)这将解释这些键名的特殊语法。

这是 keyup 事件中输入键的解决方法。

if (event.type === 'keyup') {
    //this is to handle the enter button on an ipad bluetooth keyboard
    if (event.key === 'Enter') {
        event.which = event.keyCode = 13;
    }
}