#nav {
position: sticky;
top: 0;
}
最完美的解決方案。
可惜目前瀏覽器支持還不太好。
所以附上一個 polyfill:
var Sticky = function() {
var s = [],
support = (function testSupport() {
var div = document.createElement("div");
var st = ["sticky", "-webkit-sticky"];
return st.some(function(x) {
div.style.position = x;
return div.style.position === x;
});
}());
function Sticky(o) {
var self = this;
s.push(self);
self[0] = o;
var placeholder = document.createElement("div");
self.placeholder = placeholder;
placeholder.classList.add("placeholder");
self.fixed = false;
self.posit = posit;
function posit() {
var rect;
if (self.fixed) {
rect = placeholder.getBoundingClientRect();
self.staticTop = rect.top + window.pageYOffset;
} else {
rect = o.getBoundingClientRect();
self.staticTop = rect.top + window.pageYOffset;
}
}
posit();
}
Sticky.prototype.stick = function() {
if (support)
return;
var o = this[0],
top = this.staticTop;
var placeholder = this.placeholder, fixed = this.fixed;
console.log(top);
if (top > window.pageYOffset && fixed) {
placeholder.parentNode.removeChild(placeholder);
o.classList.remove("sticky");
fixed = false;
} else if (top <= window.pageYOffset && !fixed) {
o.parentNode.insertBefore(placeholder, o);
o.classList.add("sticky");
fixed = true;
}
this.fixed = fixed;
};
if (!support) {
window.addEventListener("scroll", function() {
s.forEach(function(x) { x.stick(); });
});
window.addEventListener("resize", function() {
s.forEach(function(x) { x.posit(); });
s.forEach(function(x) { x.stick(); });
});
} else {
console.log("support");
}
return Sticky;
}();
使用方法:new Sticky(document.querySelector("#nav"));