暂时使元素不可见

时间:2016-11-22 14:38:13

标签: javascript html5 dom

我正在使用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属性,因为它会导致布局更改,而我正在构建一个布局更改不起作用的工具。

1 个答案:

答案 0 :(得分:1)

正如Lain建议的那样disable transitions makeInvisible中的元素,然后超时(1ms就足够了)重置过渡属性