我一直在玩一个固定的导航栏,但我注意到当它“自我修复”时,下面的内容会跳到页面上。 这是the JSFiddle I've been working on,如果仔细观察,你会注意到当导航栏固定在屏幕顶部时,内容会跳起~1行。我试过玩Javascript:
var win = $(window),
fxel = $('nav'),
eloffset = fxel.offset().top;
win.scroll(function() {
if (eloffset < win.scrollTop()) {
fxel.addClass("fixed");
} else {
fxel.removeClass("fixed");
}
});
但我很确定问题出在CSS中:
*{
margin: 0;
padding: 0;
}
nav {
width: 100%;
background: white;
height: 35px;
border-bottom: solid 1px #E8E8E8;
}
nav.fixed {
position:fixed;
top: 0;
right:0px;
left:0px;
z-index:999;
height: 30px;
border-bottom: solid 1px #E8E8E8;
padding-bottom: 5px;
}
h1{
font-family: 'Lobster', cursive;
font-size: 50px;
text-align: center;
}
任何有关如何解决跳跃的解决方案都会非常有用。
对于参考,我试图得到类似this的东西,其中页面的顶部不是导航栏的一部分。
答案 0 :(得分:1)
当元素设置为position: fixed
时,它不再占用页面上的空间,这意味着它不会在页面上向下推送其他元素。因此,只要您的javascript添加了fixed
类,该元素就不再占用空间,因此其他内容会跳起来占据它所在的位置。
要抵消这一点,您可能需要添加另一个规则,以便向下一个元素添加类似上边距的内容。上边距需要是(现在)固定元素的高度,加上固定元素中的任何填充和边距:
https://jsfiddle.net/h6g33wne/8/
nav.fixed + * {
margin-top: 35px;
}