javascript - 固定 div 的内容随着其他 div 的滚动而改变

标签 javascript jquery html css

我正在尝试在包含博客文章信息(发布日期、注释数量、固定链接等)的布局顶部修复一个 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/

相关文章:

javascript - 增量变量在我的函数中不起作用

javascript - 将数据从 Python 脚本发送到浏览器(在 Linux 上的 xserver 下)

jquery - 显示/隐藏事件行的内容

javascript - 在 jQuery 中知道何时单击 facebook 按钮

php - 使用 $id 更新内容不起作用

javascript - 使用 javascript 在鼠标悬停时显示图像的灰度版本。在 Firefox 中可能吗?

javascript - 将变量值从 php 传递到 Angular javascript

javascript - chrome中如何获取当前事件元素?

javascript - 如何在不移动 Canvas 的情况下定位 .container?

javascript - Jquery最后一次点击