admin管理员组

文章数量:1426797

I created a sticky header for my page:

$(document).ready(() => {
  initNavbarScroll();
});

function initNavbarScroll() {
  const navbar = $("#navbar");
  const navbarTopOffset = navbar.offset().top;
  const stickedCls = "navbarSticked";

  $(window).scroll(() => {
    const isSticked = navbar.hasClass(stickedCls);
    const windowScrolledDown = $(window).scrollTop() > navbarTopOffset;

    if (windowScrolledDown) {
      if (!isSticked) {
        navbar.addClass(stickedCls);
      }
    } else {
      if (isSticked) {
        navbar.removeClass(stickedCls);
      }
    }
  });
}
body {
  margin: 0;
}

#navbar {
  height: 60px;
  width: 100%;
  background: blue;
}

.navbarSticked {
  position: fixed;
  top: 0;
}

.box {
  height: 100px;
  border-bottom: 1px solid;
  background: red;
}
<script src=".1.0/jquery.min.js"></script>
<div id="navbar"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

I created a sticky header for my page:

$(document).ready(() => {
  initNavbarScroll();
});

function initNavbarScroll() {
  const navbar = $("#navbar");
  const navbarTopOffset = navbar.offset().top;
  const stickedCls = "navbarSticked";

  $(window).scroll(() => {
    const isSticked = navbar.hasClass(stickedCls);
    const windowScrolledDown = $(window).scrollTop() > navbarTopOffset;

    if (windowScrolledDown) {
      if (!isSticked) {
        navbar.addClass(stickedCls);
      }
    } else {
      if (isSticked) {
        navbar.removeClass(stickedCls);
      }
    }
  });
}
body {
  margin: 0;
}

#navbar {
  height: 60px;
  width: 100%;
  background: blue;
}

.navbarSticked {
  position: fixed;
  top: 0;
}

.box {
  height: 100px;
  border-bottom: 1px solid;
  background: red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="navbar"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

The header should be the same as on this page.

As you can see in the code example above the transition of the header is not smooth it's a bit clunky.

How can I make it stick smoothly?

Share Improve this question edited Jul 1, 2018 at 8:55 user7637745 9852 gold badges14 silver badges27 bronze badges asked Jul 1, 2018 at 8:26 Question3rQuestion3r 3,88229 gold badges123 silver badges245 bronze badges 1
  • I use the chrome browser – Question3r Commented Jul 1, 2018 at 8:35
Add a ment  | 

1 Answer 1

Reset to default 4

You could try using css position:sticky; instead of position:fixed

https://css-tricks./position-sticky-2/

本文标签: javascriptCreate smooth sticky header transition with CSSStack Overflow