Check if element is visible in DOM

后端 未结 18 2114

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

    Improving on @Guy Messika's answer above, breaking and returning false if the center point' X is < 0 is wrong as the element right side may go into the view. here's a fix:

    private isVisible(elem) {
        const style = getComputedStyle(elem);
    
        if (style.display === 'none') return false;
        if (style.visibility !== 'visible') return false;
        if ((style.opacity as any) === 0) return false;
    
        if (
            elem.offsetWidth +
            elem.offsetHeight +
            elem.getBoundingClientRect().height +
            elem.getBoundingClientRect().width === 0
        ) return false;
    
        const elementPoints = {
            center: {
                x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
                y: elem.getBoundingClientRect().top + elem.offsetHeight / 2,
            },
            topLeft: {
                x: elem.getBoundingClientRect().left,
                y: elem.getBoundingClientRect().top,
            },
            topRight: {
                x: elem.getBoundingClientRect().right,
                y: elem.getBoundingClientRect().top,
            },
            bottomLeft: {
                x: elem.getBoundingClientRect().left,
                y: elem.getBoundingClientRect().bottom,
            },
            bottomRight: {
                x: elem.getBoundingClientRect().right,
                y: elem.getBoundingClientRect().bottom,
            },
        };
    
        const docWidth = document.documentElement.clientWidth || window.innerWidth;
        const docHeight = document.documentElement.clientHeight || window.innerHeight;
    
        if (elementPoints.topLeft.x > docWidth) return false;
        if (elementPoints.topLeft.y > docHeight) return false;
        if (elementPoints.bottomRight.x < 0) return false;
        if (elementPoints.bottomRight.y < 0) return false;
    
        for (let index in elementPoints) {
            const point = elementPoints[index];
            let pointContainer = document.elementFromPoint(point.x, point.y);
            if (pointContainer !== null) {
                do {
                    if (pointContainer === elem) return true;
                } while (pointContainer = pointContainer.parentNode);
            }
        }
        return false;
    }
    

提交回复
热议问题