【发布时间】:2018-12-18 04:37:02
【问题描述】:
我正在开发一个简单的游戏,其中用户单击“开始”按钮,该按钮被禁用,然后用户使用箭头键盘在画布上执行一些操作。它在 Chrome 中按预期工作,但我在 Firefox 中观察到一个奇怪的行为。即,禁用按钮后,在我单击它的某个位置之前,不会在页面上触发“keydown”事件。看起来禁用按钮后,页面失去焦点或其他东西。
这种行为符合规范,还是 Firefox DOM 事件调度错误?
Firefox 64.0、Ubuntu
const button = document.querySelector('button');
const canva = document.querySelector('.canva');
const doc = document.documentElement;
doc.addEventListener('keydown', evt => {
canva.innerHTML = evt.key;
});
button.addEventListener('click', evt => {
button.disabled = true;
});
body {
font-family: sans-serif;
margin: 0;
background-color: #F4511E;
}
button {
display: block;
text-align: center;
width: 100px;
margin: 10px auto;
}
.canva {
background-color: white;
width: 200px;
height: 200px;
margin: auto;
font-size: 1.5em;
font-weight: bald;
line-height: 200px;
text-align: center;
}
<!doctype html>
<html>
<head>
<title>Lost events</title>
<meta charset="UTF-8">
</head>
<body>
<button>Start</button>
<div class="canva"></div>
</body>
</html>
【问题讨论】:
-
您使用的是哪个版本的 firefox,因为它在 macOS firefox (v64.0) 上按预期工作
-
可在 Firefox 开发版 65.0b4 中重现
-
@front_end_dev, Firefox 64.0, Ubuntu
-
无法在 65 macOS 上重现。如果您直接在
document上收听会怎样?登录document.activeElement时会输出什么? -
@Kaiido,谢谢。
document.activeElement在页面加载后是<body>。在点击按钮并禁用后:在 Chrome 上 - 它仍然是<body>,但在 Firefox 上它是禁用按钮。所以看起来禁用按钮就像 DOM 事件的黑洞)document.activeElement.blur()使<body>再次激活并解决问题
标签: javascript firefox dom-events