我有以下代码;
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/