jQuery粘性导航栏

时间:2015-09-30 16:27:14

标签: jquery navbar sticky

我正在尝试制作一个粘贴导航栏,只有当它触及顶部时才会粘到顶部,但是我的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');
        }
    });
});

链接到jsFiddle: http://jsfiddle.net/fj10ruqs/

2 个答案:

答案 0 :(得分:2)

当窗口滚动处理程序运行时,不会重新计算距离。您需要将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');
        }
    });

答案 1 :(得分: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");
  }
}