有什么方法,我可以检查如果一个元素是可见的纯JS(没有jQuery) ?

因此,给定一个DOM元素,我如何检查它是否可见?我试着:

window.getComputedStyle(my_element)['display']);

但这似乎并不奏效。我想知道我应该检查哪些属性。我想到了:

display !== 'none'
visibility !== 'hidden'

还有我可能漏掉的吗?


当前回答

所以我找到了最可行的方法:

function visible(elm) {
  if(!elm.offsetHeight && !elm.offsetWidth) { return false; }
  if(getComputedStyle(elm).visibility === 'hidden') { return false; }
  return true;
}

这是基于以下事实:

显示:所有元素(即使是嵌套的元素)都没有宽度和高度。 可见性即使对于嵌套的元素也是隐藏的。

因此不需要测试offsetParent或在DOM树中循环来测试哪个父对象具有可见性:hidden。这应该可以在ie9中工作。

你可能会说,如果透明度:0和折叠的元素(有宽度但没有高度-反之亦然)也不是真正可见的。但话说回来,它们并不是隐藏的。

其他回答

结合上面的几个答案:

function isVisible (ele) {
    var style = window.getComputedStyle(ele);
    return  style.width !== "0" &&
    style.height !== "0" &&
    style.opacity !== "0" &&
    style.display!=='none' &&
    style.visibility!== 'hidden';
}

就像AlexZ说的,这可能会比你的一些其他选择更慢,如果你更具体地知道你在寻找什么,但这应该抓住所有隐藏元素的主要方式。

但是,这也取决于你认为什么是可见的。例如,一个div的高度可以设置为0px,但内容仍然可见,这取决于溢出属性。或者,可以将div的内容设置为与背景相同的颜色,这样用户就不会看到它,但仍然可以在页面上显示。或者一个div可以移出屏幕或隐藏在其他div后面,或者它的内容可以是不可见的,但边界仍然可见。在一定程度上,“可见”是一个主观术语。

这就是我所做的:

HTML和CSS:默认情况下使元素隐藏

<html>
<body>

<button onclick="myFunction()">Click Me</button>

<p id="demo" style ="visibility: hidden;">Hello World</p> 

</body>
</html> 

JavaScript:增加了一个代码来检查可见性是否被隐藏:

<script>
function myFunction() {
   if ( document.getElementById("demo").style.visibility === "hidden"){
   document.getElementById("demo").style.visibility = "visible";
   }
   else document.getElementById("demo").style.visibility = "hidden";
}
</script>

使用与jQuery相同的代码:

jQuery.expr.pseudos.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

在函数中:

function isVisible(e) {
    return !!( e.offsetWidth || e.offsetHeight || e.getClientRects().length );
}

在我的Win/IE10、Linux/Firefox中工作得很好。45岁的Linux / Chrome.52……

感谢没有jQuery的jQuery!

下面是一个(纯纯的JS)函数,它执行大量的检查,确保给定的元素对用户可见:

function isVisible(element) {
    // Check if the element is null or undefined
    if (!element) return false;

    // Get the element's bounding client rect
    const boundingRect = element.getBoundingClientRect();

    // Check if the element has a positive width and height
    if (boundingRect.width <= 0 || boundingRect.height <= 0) return false;

    // Check if the element's top and left values are within the viewport
    const top = boundingRect.top;
    const left = boundingRect.left;
    const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
    if (top > viewportHeight || left > viewportWidth) return false;

    // Check if the element's right and bottom values are within the viewport
    const right = boundingRect.right;
    const bottom = boundingRect.bottom;
    if (right < 0 || bottom < 0) return false;

    // Check if the element is hidden by the overflow property
    const parentNode = element.parentNode;
    if (parentNode && getComputedStyle(parentNode).overflow === 'hidden') {
        const parentRect = parentNode.getBoundingClientRect();
        if (top < parentRect.top || bottom > parentRect.bottom || left < parentRect.left || right > parentRect.right) {
            return false;
        }
    }

    const elementComputedStyle = getComputedStyle(element);

    // Check if the element has a z-index of less than 0
    const zIndex = elementComputedStyle.zIndex;
    if (zIndex < 0) return false;

    // Check if the element has a display value of 'none' or an opacity of 0
    const display = elementComputedStyle.display;
    const opacity = elementComputedStyle.opacity;
    if (display === 'none' || opacity === '0') return false;

    // Check if the element is hidden by an ancestor element with a display value of 'none' or an opacity of 0
    let ancestorElement = element.parentElement;
    while (ancestorElement) {
        const ancestorComputedStyle = getComputedStyle(ancestorElement);
        const ancestorDisplay = ancestorComputedStyle.display;
        const ancestorOpacity = ancestorComputedStyle.opacity;
        if (ancestorDisplay === 'none' || ancestorOpacity === '0') return false;
        ancestorElement = ancestorElement.parentElement;
    }

    // Initialize a variable to keep track of whether the element is obscured by another element
    let obscured = false;

    // Check if the element is obscured by another element according to its position
    if (elementComputedStyle.position === 'absolute' || elementComputedStyle.position === 'fixed' ||
        elementComputedStyle.position === 'relative' || elementComputedStyle.position === 'sticky' ||
        elementComputedStyle.position === 'static') {
        let siblingElement = element.nextElementSibling;
        while (siblingElement) {
            if (siblingElement.getBoundingClientRect().top > boundingRect.bottom || siblingElement.getBoundingClientRect().left > boundingRect.right) {
                break;
            }
            if (siblingElement.getBoundingClientRect().bottom > boundingRect.top && siblingElement.getBoundingClientRect().right > boundingRect.left) {
                obscured = true;
                break;
            }
            siblingElement = siblingElement.nextElementSibling;
        }
        if (obscured) return false;
    }

    // If all checks have passed, the element is visible
    return true;
}

所以我找到了最可行的方法:

function visible(elm) {
  if(!elm.offsetHeight && !elm.offsetWidth) { return false; }
  if(getComputedStyle(elm).visibility === 'hidden') { return false; }
  return true;
}

这是基于以下事实:

显示:所有元素(即使是嵌套的元素)都没有宽度和高度。 可见性即使对于嵌套的元素也是隐藏的。

因此不需要测试offsetParent或在DOM树中循环来测试哪个父对象具有可见性:hidden。这应该可以在ie9中工作。

你可能会说,如果透明度:0和折叠的元素(有宽度但没有高度-反之亦然)也不是真正可见的。但话说回来,它们并不是隐藏的。