You can check if you've scrolled down to the footer, then remove the stick
class:
function sticky_relocate() {
var window_top = $(window).scrollTop();
var footer_top = $("#footer").offset().top;
var div_top = $('#sticky-anchor').offset().top;
var div_height = $("#sticky").height();
if (window_top + div_height > footer_top)
$('#sticky').removeClass('stick');
else if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
(you could combine the if to remove the duplicate .removeClass, here for demonstration)
However, with your css you get a nasty 'jump' around when you start scrolling - in your fiddle, the right content appears below #sticky then when you stick #sticky, the right content jumps to fill the gap. Using the code above, you'll get some race-conditions as the offset() moves when it fills/unfills the gap.
To fix this gap, just add a float:left
to your #sticky css.
Updated fiddle: http://jsfiddle.net/0mLzseby/472/
I suspect you would like to go one step further and, when you get to the bottom, the div then starts to scroll with the page. You can do this by adjusting the 'position:fixed' top of .stick
. Don't forget to reset it when not below the footer:
function sticky_relocate() {
var window_top = $(window).scrollTop();
var footer_top = $("#footer").offset().top;
var div_top = $('#sticky-anchor').offset().top;
var div_height = $("#sticky").height();
var padding = 20; // tweak here or get from margins etc
if (window_top + div_height > footer_top - padding)
$('#sticky').css({top: (window_top + div_height - footer_top + padding) * -1})
else if (window_top > div_top) {
$('#sticky').addClass('stick');
$('#sticky').css({top: 0})
} else {
$('#sticky').removeClass('stick');
}
}
The padding just makes it start scrolling in a more natural place - you can probably get this from other css attributes such as margin and padding of the other components.
Updated fiddle: http://jsfiddle.net/0mLzseby/473/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…