admin管理员组

文章数量:1391929

Is there any way to know if an element is visible on an html page?

Like this:

One can probably do it considering the horizontal/vertical scrolling positions, the width/height of the browser window and the position/size of the element on the page, but I have little experience in jQuery so I don't know how to do it. And there might be a simple function one can call, I don't know.

Is there any way to know if an element is visible on an html page?

Like this:

One can probably do it considering the horizontal/vertical scrolling positions, the width/height of the browser window and the position/size of the element on the page, but I have little experience in jQuery so I don't know how to do it. And there might be a simple function one can call, I don't know.

Share Improve this question edited Apr 9, 2013 at 8:18 dsgriffin 68.7k17 gold badges140 silver badges138 bronze badges asked Mar 29, 2013 at 14:05 AlexAlex 5,1194 gold badges41 silver badges74 bronze badges 2
  • possible duplicate of How to check if an element is in the view of the user with jquery – BenM Commented Mar 29, 2013 at 14:07
  • 2 stackoverflow./questions/8229291/…. Nicely posed question though. – nickhar Commented Mar 29, 2013 at 14:08
Add a ment  | 

2 Answers 2

Reset to default 5

You can use the .is(':visible') selectors to check if an element is currently visible in the DOM.

Edit:

However, as @BenM mentioned, this doesn't check if the elements on your page are actually out of your scrollable range - a great little plugin you could use in that case would be Viewport Selectors for jQuery.

Here is some code that I use to do this. It has been tested to work great.

function isVisible($obj) {
    var top = $(window).scrollTop();
    var bottom = top + $(window).height();
    var objTop = $obj.offset().top;
    var objBottom = objTop + $obj.height();

    if(objTop < bottom && objBottom > top) {
        //some part of $obj is visible on the screen.
        //does not consider left/right, only vertical.
    }
}

本文标签: javascriptTest if element can be seen by the user on an html pageStack Overflow