jQuery 粘性导航栏

jQuery sticky navbar

我正在尝试制作一个只有在触及顶部时才会粘在顶部的粘性导航栏,但我的 jQuery 代码无法正常工作。

代码(jQuery):

function findDistance()
{
    var distToTop = $(window).scrollTop();
    var navOffset = $('#navbar').offset().top;
    var distance = (navOffset - distToTop);
    return distance;
}
$(document).ready(function()
{
    var defaultNavDist = 166;
    var distance = findDistance();
    var fixedSet = false;
    $(window).scroll(function()
    {
        if(distance < 1 && fixedSet == false)
        {
            fixedSet = true;
            $('#navbar').css('position', 'fixed');
        }
    });
});

Link 到 jsFiddle: http://jsfiddle.net/fj10ruqs/

当 window 滚动处理程序运行时,不会重新计算距离。您需要将 distance = findDistance(); 放入滚动处理程序中。当你将它固定到顶部时,你可能还想添加 $('#navbar').css('top', '0'); 以便它位于顶部。

 $(window).scroll(function()
    {
        distance = findDistance();
        if(distance < 1 && fixedSet == false)
        {
            fixedSet = true;
            $('#navbar').css('position', 'fixed');
            $('#navbar').css('top', '0');
        }
    });

我试过了,它完全适合我。`

CSS

#navbar {
    margin-top:120px; 
  overflow: hidden;
  background-color: #333;
  z-index: 9999;
}

/* Navbar links */
#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}

/* Page content */
.content {
  padding: 16px;
}

/* The sticky class is added to the navbar with JS when it reaches its scroll position */
.sticky {
  position: fixed;
  top: 0;
  width: 100%
}

/* Add some top padding to the page content to prevent sudden quick movement (as the navigation bar gets a new position at the top of the page (position:fixed and top:0) */
.sticky + .content {
  padding-top: 80px;
} 

JS

// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};

// Get the navbar
var navbar = document.getElementById("navbar");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}