开发者

DIVs that are aware of their position, or the window's scroll position?

开发者 https://www.devze.com 2023-03-10 02:29 出处:网络
In jQuery, how do you make it so a DIV will stay put until the user scrolling down would make it no longer visible (at which point开发者_JAVA百科 it sets its own CSS position to \"fixed\")? It\'s a tr

In jQuery, how do you make it so a DIV will stay put until the user scrolling down would make it no longer visible (at which point开发者_JAVA百科 it sets its own CSS position to "fixed")? It's a trick I see a lot, just not sure how it's done.

Example: http://www.yelp.com/search?find_desc=sushi&ns=1&find_loc=San+Francisco%2C+CA


Here's a quick example of some code:

var standardPosition = $('div').offset().top;

$(window).scroll(function() {
    if ($(this).scrollTop() > standardPosition) $('div').css('position','fixed');
    else $('div').css('position','relative');
});

It's important to store the starting position somewhere, so you know when you've scrolled up far enough to restore it to whatever position it was in.

http://jsfiddle.net/qC6HB/


You're looking for a Sticky Scroller. Take a look at this: jQuery Sticky Scroller / Position:Fixed Plugin

Simple Demo


Check with $(window).scroll() the Y-position of the window, and once it reaches > than the Y-position of the div element (which you can get with offset()) you can change the css to fixed.

Something like this:

$(window).scroll(function(e){
    var e = $('div').offset();
    if ($(window).scrollTop() > e.top){
     $('div').css('position','fixed').css('top',0);   
    }else{
    $('div').css('position','static');  
    }


});

Example: http://jsfiddle.net/niklasvh/HUxVC/

0

精彩评论

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

关注公众号