当页面在div内滚动时jquery保持div在视图中
我在页面右侧有一个链接列表,单击该链接会加载ajax内容
,因为链接列表比内容长,我想始终将加载的内容保持在视图中,
我使用以下代码来执行此操作,
$(window).scroll(function(){
$("#answertext")
.stop()
.animate({"marginTop": ($(window).scrollTop() - 500) + "px"}, "slow" );
});
问题是我想将其保留在其持有的 div 中,此时,如果我滚动到页面顶部,则 div 会离开其包含的 div 并悬停在上面的内容上。
查看他的 url 以查看问题(单击新闻项以加载 ajax 内容,然后滚动页面) 演示
更新:
谢谢locrizak,稍微编辑了您的代码:
正如您所做的那样,在 _offset 声明中发出 # 最初它什么也没做,所以我将 _offset 更改为包含 div '#tabpage5' 的偏移量 现在,在加载内容时,它会将 div 放置在正确的位置。
var tp5_offset = $("#tabpage5").offset();
if ( $(window).scrollTop() > tp5_offset.top ){
$("#answertext")
.stop()
.animate({"marginTop": ($(window).scrollTop() - tp5_offset.top) + "px"}, "slow" );
}
虽然我希望它随着窗口滚动而滚动,但保持在 #tabpage5 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 within the confines of the #tabpage5 div. any ideas on how to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将此行更改如下:
Change this line as follows:
试试这个:
这应该将内容粘贴在顶部内容区域。
更新
您可以这样做:
由于您不断地使右侧的 div 变大,因此引用左侧高度的 div 更好,因为它没有改变。
让我知道这是如何运作的。
Try this:
That should stick the content at the top content area.
Update
You could do something like this:
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.