我有以下代码;
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。
如果您绝对需要依赖于此代码,那么一个hack就是跟踪自己的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>