HTML元素的实际大小n Javascript

时间:2015-06-25 09:53:51

标签: javascript html css

有没有办法让10000%确保HTML元素不可见? 我正在做的那一刻:

var rect = element.getBoundingClientRect();

if (element.style.visibility !== 'hidden') && atLeastTen(element.clientWidth,
        element.clientHeight, element.offsetWidth, element.offsetHeight,
        element.scrollWidth, element.scrollHeight, rect.height, rect.width) {
    console.log("Element is visibile!");
    return true;
} else {
    console.log("Element is invisible!");
    return false;
}

function atLeastTen() {
    for (var i = 0; i < arguments.length; i++) {
        var v = arguments[i];
        console.log("CHECKING V:", v);
        if (v < 10) return false;
    }
    return true;
}

然而,这感觉有点蹩脚...... 想法?

1 个答案:

答案 0 :(得分:1)

You might need to check two things:

  1. Visibility to eyes and DOM:
    1. Check display.
    2. Check visibility.
    3. Check opacity.
  2. Whether it is inside the viewport.
    1. Get the co-ordinates and dimensions of the element.
    2. Get the dimensions of the viewport.
    3. Create a range of both.
    4. Check for intersection.

You may need to do everything for its parents too!!!

You can easily translate this into JavaScript using jQuery or none. And just checked with :visible from jQuery, the docs say:

We’ve changed the logic behind the :visible and :hidden selectors (which were used throughout jQuery to determine the visibility of an element).

This is how the logic has changed:

  • In jQuery 1.3.1 (and older) an element was visible if its CSS “display” was not “none”, its CSS “visibility” was not “hidden”, and its type (if it was an input) was not “hidden”.
  • In jQuery 1.3.2 an element is visible if its browser-reported offsetWidth or offsetHeight is greater than 0.

What does this change mean? It means that if your element’s CSS display is “none”, or any of its parent/ancestor element’s display is “none”, or if the element’s width is 0 and the element’s height is 0 then an element will be reported as hidden.

What is the benefit of making this switch? The result is two-fold:

  • The performance is much, much, better. (See below.)
  • An element is reported as “hidden” if it’s inside a “hidden” element (something that wasn’t possible before, without the use of a plugin.

In simple terms, you can check for the visibility by this small code:

$(element).is(":visible");