如何使 FF 将字符插入到由 onkeypress 处理程序添加和聚焦的输入中?

How to make FF insert character into input that was added and focused by onkeypress handler?

我有一个带有 onkeypress 处理程序的页面,该处理程序插入 input 元素并在其上设置焦点。

想法是,当用户开始输入时,输入会显示,文本会输入到这个新输入中。

这在 Chrome 67 和 IE 11 上运行良好,但在 FF (52.9.0) 上,输入的第一个字符(触发创建输入的字符)未输入到输入中。

我认为其他浏览器的行为是正确的,因为根据 w3c example onkeypress 事件发生在 "Any default actions related to this key, such as inserting a character in to the DOM" 之前,所以当执行默认操作时,新输入应该已经有了重点。然而,这在 FF 中不起作用。

我已将问题简化为这个测试用例:

<html>
<head>
   <script>
       var input = null;
       function cancelEdit() {
           document.body.removeChild(input);
           input = null;
       }
       function handleKeyPress(e) {
           if (input === null) {
               input = document.createElement("input");
               input.addEventListener("blur", cancelEdit);
               document.body.appendChild(input);
               input.focus();
           }
       }
    </script> 
</head>
<body onkeypress="handleKeyPress(event)">
    Press a key to start editing
</body>

这也可以作为 jsfiddle

现在的问题是:如何使其在 FF 中的行为与在其他浏览器中的行为相同?

我的浏览器版本:Chrome67,IE 11,FF 52.9.0。全部在 Windows 7.

虽然我现在无法在 IE11 上进行测试。你可以尝试改变 onkeypressonkeydown

在 Chrome 最新版和 Firefox 61 上测试了它(在更改之前问题被复制)