固定div的内容随其他divs滚动而改变
问题描述:
我试图修复布局顶部的一个div,该div包含博客文章的信息(发布日期,注释数量,固定链接等)并更改此信息在您向下滚动过去帖子时。我不确定它是否需要任何类型的JavaScript或使用css进行一些复杂的定位。以下是我将如何布置帖子。在帖子滚过它时,如何从每个帖子中获取特定帖子信息以在该固定div内进行更改?固定div的内容随其他divs滚动而改变
#container {
width: 960px;
margin: 0px auto;
}
#changingpostinformation {
position: fixed;
margin: 0px auto;
}
<div id="container">
<div id="changingpostinformation">fixed post information div that's information changes as each post below reaches the top of #container</div>
<div class="post">
<h3>Post Title>
<p>This is the body of this example post.</p>
</div>
<div class="post">
<h3>Post Title>
<p>This is the body of this example post.</p>
</div>
</div>
答
像@ShankarSangoli说,你应该添加top: 0;
,也left: 0;
到#changingpostinformation
(或其他值来定位它,只要你喜欢)
你”我需要一些JavaScript来找出哪个帖子首先出现在页面上并显示它的信息。
$(function() {
$(window).bind('load resize scroll', function() {
var doctop = $('body').scrollTop();
// loop over all posts, from top to bottom
$('.post').each(function() {
if ($(this).position().top > doctop) {
put_postinfo_in_fixed_div($(this));
return false; // breaks from the loop
}
});
});
});
该函数在页面加载时以及窗口大小或滚动时运行一次。
你需要实现put_postinfo_in_fixed_div()
它得到一个后div,并做它说。
答
使用此CSS:
#changingpostinformation {
position: fixed;
top: 0px;
}
changingpostinformation div目前已经为每个帖子保留了帖子信息 - 这只是让它根据当前帖子提供正确信息的问题。 – Ryan 2012-02-06 20:11:33
我的代码调用'put_postinfo_in_fixed_div'并传递第一个可见的post div(作为jquery对象)。你应该实现这个功能来做你需要的任何事情。 – ori 2012-02-06 20:16:31