javascript - 为什么 document.activeElement 在 Mac 上使用 Firefox 会产生不同的结果

标签 javascript macos firefox

我有以下代码;

document.addEventListener('submit', function(e) {
  e.preventDefault();
  console.log(document.activeElement);
});
<form action="/" type="POST">
  <label>Enter text: </label><input type="text">
  <input type="submit">
</form>

在 Linux 或 Windows(Chrome 或 Firefox)上单击按钮时,控制台中的输出为 <input type="submit">

但是在 Mac Firefox 上,我得到了输出 <body> . (Chrome 会生成 <input type="submit">

为什么 Mac 版 Firefox 的输出不同?

最佳答案

这确实听起来像是一个错误,而你做对了打开 this ticket .

如果您的代码绝对需要依赖它,一种技巧是跟踪您自己的 activeElement。

:active 伪类设置正确,因此我们可以利用它来跟踪我们自己的 activeElement。

我们可以在我们试图跟踪的元素上添加一个非常快速的 CSS 转换,然后监听它们的 transitionend 事件,以便在它们变为或停止事件时进行处理。可以通过检查它们是否与转换结束时的 :active 伪类匹配来检查它们的状态。

然后,当您需要检索 document.activeElement 时,您只需首先检查您自己的 activeElement 变量是否包含某些内容,否则就回退到浏览器的报告。

此外,由于这个错误似乎只影响按钮元素,我们只能在这些元素上添加这个 hack:

let activeElement;
document.addEventListener('transitionend', function(e) {
  // if the target is currently active, it is the activeElement
  activeElement = e.target.matches(':active') ? e.target : null;
});


document.addEventListener('submit', function(e) {
  e.preventDefault();
  // first try to get our own activeElement
  // otherwise default to the document's one
  console.log('in submit', activeElement || document.activeElement);
  });
// to show the default one still works
document.addEventListener('click', function(e) {
  console.log('in click', activeElement || document.activeElement);
});
input,button { /* target only buttons UIs */
  transition: opacity 0.000001s; /* a really fast transition */
}
input:active,button:active {
  opacity: 0.999; /* a property barely noticeable */
}
<form action="/" type="POST">
  <label>Enter text: </label><input type="text">
  <button type="submit" tabindex="0">submit</button>
</form>
<a href="#">click me</a>

关于javascript - 为什么 document.activeElement 在 Mac 上使用 Firefox 会产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55929696/

相关文章:

javascript - MACD + 高线图表绘制问题

javascript - 如何防止 DOM 子级继承 addEventListener?

macos - 如何使 IKImageBrowserView Quick Look 图标看起来像 Finder 图标?

javascript - 在 JavaScript 中定义全局变量时省略 var 关键字

jquery - Firefox:模糊事件仅在所选元素外部第二次单击时触发 有什么方法可以修复它吗?

javascript - 检查用户是否使用 PassportJS/ExpressJS 登录

javascript - SVG 在最大尺寸处拉伸(stretch)然后填充其余尺寸

python - 我应该如何将 cx_freeze 与 Macports 库一起使用?

macos - 如何使 zsh 在 Mac OS X 上作为登录 shell 运行(在 iTerm 中)?

javascript - Google Analytics 片段导致 Linux Firefox 中的页面刷新