【问题标题】:DOM events are not fired after disabling element in Firefox在 Firefox 中禁用元素后不会触发 DOM 事件
【发布时间】: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 在页面加载后是 &lt;body&gt;。在点击按钮并禁用后:在 Chrome 上 - 它仍然是 &lt;body&gt;,但在 Firefox 上它是禁用按钮。所以看起来禁用按钮就像 DOM 事件的黑洞)document.activeElement.blur() 使&lt;body&gt; 再次激活并解决问题

标签: javascript firefox dom-events


【解决方案1】:

按钮获得焦点并在单击后变为document.activeElement。禁用后它在 Chrome 中自动为blur()-ed,但在 Firefox 中它继续为activeElement 并像黑洞一样吞噬事件。所以,需要在禁用activeElement后显式调用document.activeElement.blur()

感谢@Kaiido 的评论

Firefox bugtracker 中有一个关于此的问题 https://bugzilla.mozilla.org/show_bug.cgi?id=706773

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多