开发者

fixed div on bottom of page that stops in given place

I have fixed div on bottom of my page that works well. I wonder if there is some simple way to make it "stop" on some place in page when user srolls down to it. I want it to remain fixed on bottom, until user scrolls down to some defined p开发者_如何学运维lace on page and than stick it to the page and scroll like the rest of content. Any suggestions?


I tried setting something up on jsfiddle. While I was writing it up, I see that others have posted their alternatives. In case mine helps in any way: http://jsfiddle.net/PnUmM/1/

I set the position to relative in the CSS, calculate where it is on document load to keep the info aside and then set it to fixed.

var sticky_offset;
$(document).ready(function() {

    var original_position_offset = $('#sticky_for_a_while').offset();
    sticky_offset = original_position_offset.top;
    $('#sticky_for_a_while').css('position', 'fixed');


});

$(window).scroll(function () {
    var sticky_height = $('#sticky_for_a_while').outerHeight();
    var where_scroll = $(window).scrollTop();
    var window_height = $(window).height();


    if((where_scroll + window_height) > sticky_offset) {
        $('#sticky_for_a_while').css('position', 'relative');
    }

    if((where_scroll + window_height) < (sticky_offset + sticky_height))  {
        $('#sticky_for_a_while').css('position', 'fixed');
    }

});


I made this up for you: http://jsfiddle.net/XCYFG/1/.

$(document).ready(function() {
    window._div1 = $('#div1'); //selector is expensive
    window._window = $(window);
    $(window).scroll(function(e) {
        _div1.css("top",
                  Math.min(_window.height(),
                           window.scrollY + 100)
                  + _window.height() - _div1.height() - 110);
    }).scroll();
});


I have a plugin that does the opposite - it's in the flow of the webpage, and when the user scrolls past it, it gets fixed to the viewport. What it actually does though is apply a css class to the element, so you should be able to use it as is.

You can find the plugin here: https://github.com/hanssonlarsson/jquery-fixedscroll

Then I would suggest you have your element in the flow of your webpage:

<div id="sometimesFixed">content</div>

With css:

#sometimesFixed {
  position: fixed;
  bottom: 0;
}
#sometimesFixed.scroll {
  position: static;
}

And apply the plugin like so, in your JavaScript:

$('#sometimesFixed').fixedscroll({className: 'scroll'});

There is also a more general plugin, very new, called jquery-waypoints. The idea is to bind any code to "waypoints", points on the webpage where, when the user scrolls past them, some code is executed.

https://github.com/imakewebthings/jquery-waypoints

It's probably more optimized and a better fit than my plugin, but YMMV!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜