Check if element is visible in DOM

后端 未结 18 1694

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:07

    The accepted answer did not worked for me.Year 2020 answer:

    1) The (elem.offsetParent !== null) method works fine in Firefox but not in Chrome. For Chrome "position: fixed;" will also make offsetParent return "null" even the element if visible in the page.

    Demo:

    //different results in Chrome and Firefox
    console.log(document.querySelector('#hidden1').offsetParent); //null Chrome & Firefox
    console.log(document.querySelector('#fixed1').offsetParent); //null in Chrome, not null in Firefox
        
        

    you can see this guy megatest https://stackoverflow.com/a/11639664/4481831 (run it with multiple browsers to see the differences).

    2) The (getComputedStyle(elem).display !== 'none') do not work because the element can be invisible because one of the parents display property is set to none, getComputedStyle will not catch that.

    Demo:

    var child1 = document.querySelector('#child1');
    console.log(getComputedStyle(child1).display);
    //child will show "block" instead of "none"

    3) The (elem.clientHeight !== 0). This method is not influenced by position fixed and it also check if element parents are not-visible. But it has problems with simple elements that do not have a css layout, see more here

    Demo:

    console.log(document.querySelector('#div1').clientHeight); //not zero
    console.log(document.querySelector('#span1').clientHeight); //zero
    test1 div
    test2 span

    4) The (elem.getClientRects().length !== 0) that seem to overpass the problems of the previous 3 methods. However it has problems with elements that use CSS tricks (other then "display:none") to hide in the page.

    console.log(document.querySelector('#notvisible1').getClientRects().length);
    console.log(document.querySelector('#notvisible1').clientHeight);
    console.log(document.querySelector('#notvisible2').getClientRects().length);
    console.log(document.querySelector('#notvisible2').clientHeight);
    console.log(document.querySelector('#notvisible3').getClientRects().length);
    console.log(document.querySelector('#notvisible3').clientHeight);
    not visible 1
    not visible 3

    CONCLUSION: So what I have showed you is that no method is perfect. To make a proper visibility check you must use a combination of the last 3 methods.

提交回复
热议问题