我一直在试图检测:focus-within
类是否丢失。我试图通过使用addEventListener的"点击","auxclick","blur","mouseup"来检测点击。但我不知道如何检测实际文档之外的点击。例如,单击URL输入。我怎么解它?
要检测DOM元素是否丢失了:focus-within
,您可以使用focusout
事件,如下所示:
containerElement.addEventListener('focusout', function(e) {
if (e.currentTarget.contains(e.relatedTarget)) {
/* Focus will still be within the container */
} else {
/* Focus will leave the container */
}
});
当焦点完全被页面丢失时(访问URL,切换选项卡等),e.relatedTarget
不存在,因此代码只是工作。如果您想在页面失去焦点时忽略,您可以使用document.hasFocus()
检查:
containerElement.addEventListener('focusout', function(e) {
/*
If the document has lost focus,
skip the containment check
and keep the element visible.
*/
if (!document.hasFocus()) {
return;
}
if (!e.currentTarget.contains(e.relatedTarget)) {
hideSelf();
}
});
…但是,当焦点返回页面时,您必须做出反应,因此完整的(er)解决方案看起来像这样:
containerElement.addEventListener('focusout', function(e) {
const self = e.currentTarget;
/*
If the document has lost focus,
don't hide the container just yet,
wait until the focus is returned.
*/
if (!document.hasFocus()) {
window.addEventListener('focus', function focusReturn() {
/*
We want the listener to be triggered just once,
so we have it remove itself from the `focus` event.
*/
window.removeEventListener('focus', focusReturn);
/*
Test whether the active element
is within our container.
*/
if (!self.contains(document.activeElement)) {
hideSelf();
}
});
return;
}
if (!self.contains(e.relatedTarget)) {
hideSelf();
}
});