开发者

jquery keep div in view when page scrolls within a div

i have a list of links on the right of a page which when clicked loads in ajax content

as the links list is longer than the content i want to always keep the loaded content in view

i am using the following code to do this

$(window).scroll(function(){
    $("#answertext")
    .stop()
    .animate({"marginTop": ($(window).scrollTop() - 500) + "px"}, "slow" );
});

the problem is i want to keep this contained within its holding div, at the moment if i scroll to the top of the page the div leaves its containing div and hovers over content above.

have a look at his url to see the problem (click a news item to load in the ajax content, then scroll the page) Demo

UPDATE:

thanks locrizak, islightly edited your code:

as you had ,issed out the # in the _offset declaration initially it did nothing so i change the _offset to that of the containing div '#tabpage5' it now posistions the div in the correct place when loadin in the content.

var tp5_offset = $("#tabpage5").offset();
if ( $(window).scrollTop() > tp5_offset.top ){
    $("#answertext")
    .stop()
    .animate({"marginTop": ($(window).scrollTop() - tp5_offset.top) + "px"}, "slow" );
}

although i would prefer it to scroll as the window scrolls, but staying wi开发者_JS百科thin the confines of the #tabpage5 div. any ideas on how to do that?


Change this line as follows:

.animate({"marginTop": (Math.max(0, $(window).scrollTop() - 500)) + "px"}, "slow" );


Try this:

var _offset = $("answertext").offset();
if ( $(window).scrollTop() > _offset.top ){
    $("#answertext")
    .stop()
    .animate({"marginTop": ($(window).scrollTop() - _offset.top) + "px"}, "slow" );

}

That should stick the content at the top content area.

Update

You could do something like this:

var _offset = $("answertext").offset();
var _currentSpace = parseFloat($("answertext").css('marginTop')) + $("answertext").height();
var _maxHeight = $('#infotext').height() + $('#infotext').offset().top;
if ( $(window).scrollTop() > _offset.top  && _currentSpace 

Since your constantly making the div on the right bigger, referencing the div on the left height is better because its is not changing.

Let me know how that works.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜