Detect if an element is visible (without using jQuery)

前端 未结 5 729
执笔经年
执笔经年 2021-02-07 11:20

I\'m trying to detect if an html element I gave an id is visible or not without using jquery.

The context:

In the forgotten user password page,

5条回答
  •  悲&欢浪女
    2021-02-07 11:44

    I wrote this some time back. This handles a lot of cases to my knowledge. This actually checks if the element is being seen by the user in it's current state.

    Checks for display, visibility, opacity, overflow quirk and does it recursively till we go till the document node.

    function isVisible(el) {
            while (el) {
                if (el === document) {
                    return true;
                }
    
                var $style = window.getComputedStyle(el, null);
    
                if (!el) {
                    return false;
                } else if (!$style) {
                    return false;
                } else if ($style.display === 'none') {
                    return false;
                } else if ($style.visibility === 'hidden') {
                    return false;
                } else if (+$style.opacity === 0) {
                    return false;
                } else if (($style.display === 'block' || $style.display === 'inline-block') &&
                    $style.height === '0px' && $style.overflow === 'hidden') {
                    return false;
                } else {
                    return $style.position === 'fixed' || isVisible(el.parentNode);
                }
            }
        }
    

提交回复
热议问题