问题
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