I'm having problems with JQuery Offset when used inside of a div that has a fixed height and overflow.
Inside this div I have two columns, a main and a sidebar. I want one of the divs in the side bar to scroll within the div until it reaches the top, but then I want it to stay there.
I have a demo set up here : http://jsfiddle.net/zsJAr/53/
The div does scroll up but it doesn't start to stay at the top until it's scrolled past the top开发者_高级运维 of the div, effectively cutting off the top part of the div.
Any help would be greatly appreciated.
You needed the top offset where the <h1>
is:
http://jsfiddle.net/maniator/qaVnY/
$(document).ready(function() {
// move the share this widget with the window
if ($('#scrollingContent').length > 0) {
var $widget = $("#scrollingContent");
var $window = $("#overFlowDiv");
var $topOffset = $('h1').height();
var $offset = $widget.offset();
var $initialMargin = $widget.css('marginTop');
$window.scroll(function() {
if ($window.scrollTop() > ($offset.top)) {
$widget.stop().animate({
marginTop: ($window.scrollTop() - ($offset.top - $topOffset))
});
} else {
$widget.stop().animate({
marginTop: $initialMargin
});
}
});
}
})
A little less conventional, but this seemed to work for me...
$window.scroll(function() {
if ($window.scrollTop() > $offset.top) {
$widget.stop().animate({
marginTop: ($window.scrollTop() -(180 - $offset.top))
});
精彩评论