Determine visibility / real z-index of html elements

前端 未结 3 1818
孤独总比滥情好
孤独总比滥情好 2020-12-21 03:21

Is it possible to determine if an html element is visible to the user?

Example

A page has an input field with a datepicker. If the user clicks on the input

3条回答
  •  春和景丽
    2020-12-21 03:28

    I tried a different approach using elements coordinates (getBoundingClientRect) and then using elementFromPoint to see if the element is hidden or visible.

    DEMO (Follow the instruction on the right side)

            var rectPos = this.getBoundingClientRect();
    
            var result = 0;
            if (this == document.elementFromPoint(rectPos.left, 
                                                        rectPos.top)) {
                result++;
            }
            if (this == document.elementFromPoint(rectPos.left, 
                                                        rectPos.bottom - 1)) {
                result++;
            }
            if (this == document.elementFromPoint(rectPos.right - 1, 
                                                         rectPos.top)) {
                result++;
            }
            if (this == document.elementFromPoint(rectPos.right - 1, rectPos.bottom - 1)) {
                result++;
            }
    
            if (result == 4) {
                result = 'visible';
            } else if (result == 0) {
                result = 'hidden';
            } else {
                result = 'partially visible';
            }
    

    Further Readings: getBoundingClientRect, elementFromPoint

提交回复
热议问题