Check if element is visible in DOM

后端 未结 18 2106

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

提交回复
热议问题