<html>
<head>
<style>
#blog_header{
width: 100%;
height: 130px;
background: #993399;
position: fixed;
}
#nav_ul,#nav_ul li{
height: 30px;
display: inline;
line-height: 30px;
}
</style>
</head>
<body>
<div id="blog_header">
<ul id="nav_ul">
<li>news</li>
<li>technology</li>
<li>forum</li>
<li>about me</li>
</ul>
</div>
<div id="main_wrapper">
content
</div>
如让一段代码,这样导航条是会永远停留在网页最上端,但是目前的问题是fixed定位后脱离文档流了,导航条不再占位,导致下面#main_wrapper的起始位置和#blog_header一样了,请问我如何让#blog_header占位?
网上查到部分资料说放一个空div,但是感觉这样不太合适
#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"));
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。