开发者

jQuery - How to detect if an item is currently outside of the viewport?

I'm building a page that will be using ajax to update a main content area. Users will be clicking on items from a left hand menu bar to update a div to the right with search results.

I want to detect if a user has scrolled down so far causing the right-hand-side results div to moved outside the开发者_如何学Python viewport -- but has does one detect that?


No testing/cross browser assurances/example code but take a look at $elem.offset().top vs the $(document).scrollTop() - Might be your solution.

You might need the .height() of the element and the window as well.

Brodingo in #jQuery on freenode just linked me to a Viewport Selectors plugin that might simplify it.


I've had some success with the following, where a this_element that is outside of the viewport (either above or below its bounds) triggers YOUR ACTION:

function scroll_to(this_element){
    var banner_height = 145;
    var window_height = $(window).height();
    var scroll_position = $(window).scrollTop();
    var element_position = $(this_element).position().top;
    var element_height = $(this_element).height();
    if(((banner_height + element_position) < scroll_position) || ((scroll_position + window_height) < (banner_height + element_position + element_height))){
        //YOUR ACTION        
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜