I have a div containing a list of photo names. When a name is clicked, another div (outside the first one) is displayed with the photo and comments below it. When this second div is scrolled (using the main window scrollbar), I do not want the first div to scroll along, it should remain where it is. So, as soon as I open the photo div, I change the first div's position from absolute to fixed. So far so good, t开发者_如何学Gohis works fine.
However, when the first div has been scrolled before a photo is opened, the setting of this div to fixed, causes it to jump back to the top, while I want it to remain where it was. Is there a way to do this? Why does it jump to the top?
Basically I want to achieve the same as showing photo's in Facebook. The background is frozen where it is while the photo area can be scrolled.
Thanks!
The fixed div jumps to the top because having no top/bottom values basically means they're positioned at 0.
Now, to prevent this you will have to set the current position (before position
is changed to fixed
) in relation to the window (that's the key part).
See my jsfiddle
The jquery part from that:
$('#click').click(function() {
var ftop = $('#fixer').offset().top - $(window).scrollTop();
var fleft = $('#fixer').offset().left;
$('#fixer').css({position: 'fixed', left: fleft + 'px', top: ftop + 'px'});
});
Before the position is fixed, the current top coordinates [offset().top - (window).scrollTop
] are calculated and then passed to the #fixer
's top
value. The $(window).scrollTop()
is important because it makes sure the #fixer
will always be at viewpoint when fixed.
精彩评论