Get only visible element using pure javascript

后端 未结 6 569
Happy的楠姐
Happy的楠姐 2020-12-10 15:03

I have elements like below

send Message
send Message
sen
6条回答
  •  Happy的楠姐
    2020-12-10 15:45

    var $el = document.querySelectorAll('.one');
    var visibleElements;
    
    for (var i = 0; i < $el.length; i++) {
        var currentElement = $el[i];
        var $style = window.getComputedStyle(currentElement, null);
    
        if (!currentElement) {
            return false;
        } else if (!$style) {
            return false;
        } else if ($style.display === 'none') {
            return false;
        } else {
            visibleElements.push(currentElement);
        }
    }
    

    First we get all the elements using document querySelectorAll. Then, we need to iterate over all the elements. To get the style, use getComputedStyle.

    After that :visible check only for display and we do it the same way.

    A more comprehensive approach:

    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);
                }
            }
        }
    

    This would check for any possible way an element could be visible in the dom to my knowledge minus the z-index cases.

提交回复
热议问题