我正在尝试在包含博客文章信息(发布日期、注释数量、固定链接等)的布局顶部修复一个 div,并在您向下滚动过去的文章时更改此信息。我不确定它是否需要任何类型的 javascript 或仅使用 css 进行一些复杂的定位。以下是我将如何布置帖子。当帖子滚动经过它时,如何从每个帖子获取特定的帖子信息以在该固定 div 内更改?
#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,并按其说明执行操作。
关于javascript - 固定 div 的内容随着其他 div 的滚动而改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9166285/