Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - Determine visibility / real z-index of html elements

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 field, another div appears which allows the user to select the desired date.

As long the datepicker is visible it hides elements which are behind it. I need a way to tell if an element is hidden or not.

First Approach

One way would be to check and compare the z-index values. But if they are note explicitly set, they are always auto.

Another way could be a way to check if an element is visible to the user. But i can't think of any way to do so.

The :visible selector does not work in this situation, because the element is only hidden to the user's eyes but still visible.

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...