有没有办法让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;
}
然而,这感觉有点蹩脚...... 想法?
答案 0 :(得分:1)
You might need to check two things:
display
.visibility
.opacity
.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");