Check if element is visible in DOM

后端 未结 18 1692

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

    Here's the code I wrote to find the only visible among a few similar elements, and return the value of its "class" attribute without jQuery:

      // Build a NodeList:
      var nl = document.querySelectorAll('.myCssSelector');
    
      // convert it to array:
      var myArray = [];for(var i = nl.length; i--; myArray.unshift(nl[i]));
    
      // now find the visible (= with offsetWidth more than 0) item:
      for (i =0; i < myArray.length; i++){
        var curEl = myArray[i];
        if (curEl.offsetWidth !== 0){
          return curEl.getAttribute("class");
        }
      }
    
    0 讨论(0)
  • 2020-11-22 08:11

    A little addition to ohad navon's answer.

    If the center of the element belongs to the another element we won't find it.

    So to make sure that one of the points of the element is found to be visible

    function isElementVisible(elem) {
        if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
        const style = getComputedStyle(elem);
        if (style.display === 'none') return false;
        if (style.visibility !== 'visible') return false;
        if (style.opacity === 0) return false;
        if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
            elem.getBoundingClientRect().width === 0) {
            return false;
        }
        var elementPoints = {
            'center': {
                x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
                y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
            },
            'top-left': {
                x: elem.getBoundingClientRect().left,
                y: elem.getBoundingClientRect().top
            },
            'top-right': {
                x: elem.getBoundingClientRect().right,
                y: elem.getBoundingClientRect().top
            },
            'bottom-left': {
                x: elem.getBoundingClientRect().left,
                y: elem.getBoundingClientRect().bottom
            },
            'bottom-right': {
                x: elem.getBoundingClientRect().right,
                y: elem.getBoundingClientRect().bottom
            }
        }
    
        for(index in elementPoints) {
            var point = elementPoints[index];
            if (point.x < 0) return false;
            if (point.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
            if (point.y < 0) return false;
            if (point.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
            let pointContainer = document.elementFromPoint(point.x, point.y);
            if (pointContainer !== null) {
                do {
                    if (pointContainer === elem) return true;
                } while (pointContainer = pointContainer.parentNode);
            }
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-11-22 08:11

    Just for the reference it should be noted that getBoundingClientRect() can work in certain cases.

    For example, a simple check that the element is hidden using display: none could look somewhat like this:

    var box = element.getBoundingClientRect();
    var visible = box.width && box.height;
    

    This is also handy because it also covers zero-width, zero-height and position: fixed cases. However, it shall not report elements hidden with opacity: 0 or visibility: hidden (but neither would offsetParent).

    0 讨论(0)
  • 2020-11-22 08:11

    This is what I did:

    HTML & CSS: Made the element hidden by default

    <html>
    <body>
    
    <button onclick="myFunction()">Click Me</button>
    
    <p id="demo" style ="visibility: hidden;">Hello World</p> 
    
    </body>
    </html> 
    

    JavaScript: Added a code to check whether the visibility is hidden or not:

    <script>
    function myFunction() {
       if ( document.getElementById("demo").style.visibility === "hidden"){
       document.getElementById("demo").style.visibility = "visible";
       }
       else document.getElementById("demo").style.visibility = "hidden";
    }
    </script>
    
    0 讨论(0)
  • 2020-11-22 08:14

    Use the same code as jQuery does:

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

    So, in a function:

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

    Works like a charm in my Win/IE10, Linux/Firefox.45, Linux/Chrome.52...

    Many thanks to jQuery without jQuery!

    0 讨论(0)
  • 2020-11-22 08:15

    All the other solutions broke for some situation for me..

    See the winning answer breaking at:

    http://plnkr.co/edit/6CSCA2fe4Gqt4jCBP2wu?p=preview

    Eventually, I decided that the best solution was $(elem).is(':visible') - however, this is not pure javascript. it is jquery..

    so I peeked at their source and found what I wanted

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

    This is the source: https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js

    0 讨论(0)
提交回复
热议问题