您可以在窗口对象上挂钩scroll事件.处理事件时,请查看窗口/文档的垂直滚动位置(有关如何操作,请参阅SO上的
this answer).对div使用绝对定位,并根据需要将其顶部更新为坐标.
FWIW,我会非常小心这样做.通常当用户滚动时,这是因为他们想要查看与页面上的内容不同的内容.就个人而言,我讨厌在网页上跟随我的盒子. :-)但这并不意味着有时没有充分的理由这样做.
非常基本的例子(live copy):
CSS:
#box {
/* Position absolutely, 30px down from the top */
position: absolute;
top: 30px;
/* In my case I'm centering it in the window; do what you like */
margin-left: -100px;
left: 50%;
width: 200px;
/* These are just for my example */
height: 1.25em;
border: 1px solid #bbb;
text-align: center;
}
HTML:
JavaScript的:
window.onload = function() {
function getScrollTop() {
if (typeof window.pageYOffset !== 'undefined' ) {
// Most browsers
return window.pageYOffset;
}
var d = document.documentElement;
if (d.clientHeight) {
// IE in standards mode
return d.scrollTop;
}
// IE in quirks mode
return document.body.scrollTop;
}
window.onscroll = function() {
var box = document.getElementById('box'),
scroll = getScrollTop();
if (scroll <= 28) {
box.style.top = "30px";
}
else {
box.style.top = (scroll + 2) + "px";
}
};
};
(在我的情况下,我总是将它保持在顶部下方2个像素,但如果你不想这样,你可以相应地调整数字.)