在页面中间开始div,但是当用户向下滚动页面时,它仍然位于顶部?

时间:2012-04-10 20:24:46

标签: css html fixed

最好举个例子来说明我所描述的内容。

带有类别列表的div元素从页面中间开始,但是当用户向下滚动时,它仍然位于顶部?

http://www.khanacademy.org/

我知道如何制作固定元素。我的问题是如何使元素默认显示在页面的中心,但随着用户向下滚动,元素将保持在顶部。

1 个答案:

答案 0 :(得分:4)

这是我认为您正在寻找的快速 jsFiddle example 。基本上你有一个最初定位相对的div,然后当页面滚动时,位置变为固定。 jQuery使用$(window).scroll事件在这里做大量的事情。

jQuery的:

var stickerTop = parseInt($('#sticker').offset().top);
$(window).scroll(function() {
    $("#sticker").css((parseInt($(window).scrollTop()) + parseInt($("#sticker").css('margin-top')) > stickerTop) ? {
        position: 'fixed',
        top: '0px'
    } : {
        position: 'relative'
    });
});​

CSS:

body {
    width: 960px;
}
#mainbar {
    width: 660px;
    float: left;
}
#sidebar {
    width: 270px;
    float: right;
}
#sticker {
    width: 200px;
    padding: 10px;
    margin-top:25px;
    background: #eee;
    border: 1px solid #ccc;
}​