我正在开发一个简单的游戏,用户点击“开始”按钮,按钮被禁用,然后用户使用箭头键盘在 Canvas 上执行一些操作。它在 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>
最佳答案
Button 获得焦点并在点击后变为 document.activeElement
。禁用后,它会在 Chrome 中自动被 blur()
编辑,但在 Firefox 中它仍然是 activeElement
并像黑洞一样吞噬事件。因此,有必要在禁用 activeElement
document.activeElement.blur()
感谢@Kaiido 的评论
在 Firefox bugtracker 中有一个关于那个的问题 https://bugzilla.mozilla.org/show_bug.cgi?id=706773
关于javascript - 在 Firefox 中禁用元素后不会触发 DOM 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53826459/