我一直在努力让我的导航栏在滚动时保持在顶部并实现它。唯一的问题是,当执行到固定位置的导航栏转换时,我的内容会出现。
这是此行为的示例:http://jsfiddle.net/7HHa5/4/
JavaScript
window.onscroll = changePos;
function changePos() {
var header = document.getElementById("header");
if (window.pageYOffset > 70) {
header.style.position = "absolute";
header.style.top = pageYOffset + "px";
} else {
header.style.position = "";
header.style.top = "";
}
}
我正在使用 bootstrap 和 jQuery。
如何避免这种行为?
最佳答案
当您将 header 设置为 position: absolute
时,它会留下一个空白空间,该空间会被内容填充。当标题固定时,您需要在内容顶部添加边距,如下所示:
window.onscroll = changePos;
function changePos() {
var header = document.getElementById("header");
var content = document.getElementById("content");
if (window.pageYOffset > 70) {
header.style.position = "absolute";
header.style.top = pageYOffset + "px";
content.style.marginTop = '55px'
} else {
header.style.position = "";
header.style.top = "";
content.style.marginTop = '0'
}
}
参见 http://jsfiddle.net/2EhLs/1/举个例子。
不过,还有更好的办法。
既然您已经在使用 Bootstrap,您应该考虑使用内置的 Affix功能。
最好的例子是this one来自 another question :
$('#nav-wrapper').height($("#nav").height());
$('#nav').affix({
offset: { top: $('#nav').offset().top }
});
关于javascript - 当滚动过去时位置更改为固定时,导航栏使内容跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23302128/