在Firefox中禁用元素后,DOM事件不会被触发

4
我正在开发一个简单的游戏,用户点击“开始”按钮后,该按钮将被禁用,然后用户使用箭头键在画布上执行一些操作。在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)上正常工作。 - front_end_dev
可在Firefox Dev Edition 65.0b4中重现 - ack_inc
@front_end_dev,Firefox 64.0,Ubuntu - vatosarmat
3
无法在 macOS 65 上重现。如果直接在 "document" 上监听,会发生什么?当记录 document.activeElement 时输出了什么? - Kaiido
@Kaiido,谢谢。在页面加载后,document.activeElement<body>。在按钮点击和禁用之后:在 Chrome 上,它仍然是 <body>,但在 Firefox 上,它是禁用的按钮。因此,看起来禁用的按钮就像 DOM 事件的黑洞)document.activeElement.blur() 使 <body> 再次活跃,并解决了问题。 - vatosarmat
1个回答

4
点击按钮后,它会获得焦点并成为document.activeElement。在禁用后,Chrome会自动调用blur(),但是在Firefox中,它仍然保持为activeElement并且会像黑洞一样吞噬事件。因此,在禁用activeElement后需要显式调用document.activeElement.blur()
感谢@Kaiido的评论。
Firefox bugtracker中有一个关于此问题的问题:https://bugzilla.mozilla.org/show_bug.cgi?id=706773

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接