HTML fixed 导航栏,css 通过fixed定位制作导航条的问题

#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"));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值