making a div start mid page, but as user scrolls down the page, it remains at the top?

大兔子大兔子 提交于 2020-01-03 03:06:13

问题


Better to give an example, to illustrate what i am describing.

The div element with the list of categories starts mid page, but as the user scrolls down it remains at the top?

http://www.khanacademy.org/

I know how to make a fixed element. My question is how do i make the element appear by default in the center of the page, but as the user scrolls down, the element will stay at the top.


回答1:


Here's a quick jsFiddle example of what I think you're looking for. Basically you have a div that is initially positioned relative, then as the page is scrolled, the position is changed to fixed. jQuery does the heavy liting here with the $(window).scroll event.

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;
}​


来源:https://stackoverflow.com/questions/10095936/making-a-div-start-mid-page-but-as-user-scrolls-down-the-page-it-remains-at-th

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!