Check if element is visible in DOM

后端 未结 18 2086

Is there any way that I can check if an element is visible in pure JS (no jQuery) ?

So, for example, in this page: Performance Bikes, if you hover over Deals (on the

18条回答
  •  忘掉有多难
    2020-11-22 08:10

    Combining a couple answers above:

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

    Like AlexZ said, this may be slower than some of your other options if you know more specifically what you're looking for, but this should catch all of the main ways elements are hidden.

    But, it also depends what counts as visible for you. Just for example, a div's height can be set to 0px but the contents still visible depending on the overflow properties. Or a div's contents could be made the same color as the background so it is not visible to users but still rendered on the page. Or a div could be moved off screen or hidden behind other divs, or it's contents could be non-visible but the border still visible. To a certain extent "visible" is a subjective term.

提交回复
热议问题