我正在使用document.elementFromPoint
API来获取某个点的元素。但我不想拥有所有元素 - 有些元素不合格,比如inline
元素。因此,我正在使不合格的元素暂时不可见,以便抓住它下面的元素。
这是一段代码摘录。
import { elementQualified, elementFromPoint } from './utils';
function makeInvisible(element) {
let oldVisibility = element.style.visibility;
/* this is supposed to make the element invisible immediately, without
* any delay. When a `transition` property is set which includes the
* `visibility` property, this is sometimes unfortunately not the case. */
element.style.visibility = "hidden";
/* this is the undo function being called at the end. */
return () => {
element.style.visibility = oldVisibility;
};
}
export default function(x, y) {
var undo = [], element, last;
/* in a loop, we grab the top-most element that is at a certain coordinate
* inside the viewport. The `last` variable is preventing an infinite loop
* in cases, where `makeInvisible()` does not work. */
while (((element = elementFromPoint(x, y)) !== null) && (last !== element)) {
/*
* In order to be qualified, this element including its ancestors must
* all be qualified. For instance, if this is a block element but the
* parent for some reason is an inline element, this is not desired. */
if (withAncestors(element).every(elementQualified)) {
break;
}
/* if the element is not qualified, we make it invisible and add it to the
* start of the `undo` array which is being batch-called after this loop. */
undo.unshift(makeInvisible(element));
/* and the loop protection */
last = element;
}
/* undo all changes */
undo.forEach((fn) => fn());
/* check if we broke the loop or we have selected the topmost element
* in which case we discard the result. */
if ((last === element) || (element === document.documentElement)) {
return null;
}
return element;
}
如果应该变为不可见的元素具有包含transition
属性的visibility
属性集,则它不会立即变为不可见。以transition: all 0.3s ease-in-out
为例。将element.style.visibility
设置为hidden
后,将需要0.3s
,之后元素实际上不可见,document.elementFromPoint
将选择其下方的元素。结果,循环中断,因为document.elementFromPoint
返回相同元素的两倍。
我不打算暂时设置display
属性,因为它会导致布局更改,而我正在构建一个布局更改不起作用的工具。