简体   繁体   English

Javascript固定导航栏跳转

[英]Javascript Fixed Navigation Bar Jumping

I've been playing around with a fixed navigation bar, but I've noticed that when it "fixes" itself, the content below all jumps up on the page. 我一直在使用固定的导航栏,但是我注意到,当它“修复”自身时,所有下面的内容都会在页面上跳转。 This is the JSFiddle I've been working on , if you look closely you'll notice that when the nav bar becomes fixed to the top of the screen, the content jumps up ~1 line. 这是我一直在研究的JSFiddle ,如果您仔细观察,您会注意到当导航栏固定在屏幕顶部时,内容向上跳〜1行。 I've tried playing around with the Javascript: 我试过玩Javascript:

 var win      = $(window),
    fxel     = $('nav'),
    eloffset = fxel.offset().top;


win.scroll(function() {
    if (eloffset < win.scrollTop()) {
        fxel.addClass("fixed");
    } else {
        fxel.removeClass("fixed");
    }
});

but I'm fairly certain the problem is in the CSS: 但我相当确定问题出在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;
}

Any solutions on how to fix the jumping would be really helpful. 任何有关如何解决跳跃问题的解决方案都将非常有帮助。

For refrence, I'm trying to get something sort of like this where the very top of the page isn't part of the navbar. 为了方便起见,我正在尝试获得类似这样的内容 ,其中页面的顶部不是导航栏的一部分。

When an element is set to position: fixed , it no longer takes up space on the page, meaning it won't push other elements down on the page. 将元素设置为position: fixed ,它将不再占用页面上的空间,这意味着它不会将其他元素向下推到页面上。 So as soon as your javascript adds the fixed class, the element no longer takes up space, and so the other content jumps up to take the place where it was. 因此,一旦您的javascript添加了fixed类,该元素就不再占用空间,因此其他内容也会跳到原来的位置。

To offset this, you may need to add another rule to add something like a top margin to the next element. 为了弥补这一点,您可能需要添加另一条规则,以向下一个元素添加诸如上边距的内容。 The top margin will need to be the height of the (now) fixed element, plus any padding and margin in the fixed element: 上边距必须是(现在)固定元素的高度,加上该固定元素中的所有填充和边距:

https://jsfiddle.net/h6g33wne/8/ https://jsfiddle.net/h6g33wne/8/

nav.fixed + * {
  margin-top: 35px;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM