【问题标题】:jQuery sticky navbarjQuery 粘性导航栏
【发布时间】:2015-09-30 16:27:14
【问题描述】:

我正在尝试制作一个只有在触及顶部时才会粘在顶部的粘性导航栏,但我的 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/

【问题讨论】:

  • JSFiddle 或类似的东西将有助于调试和提供修订。
  • 这是您要的小提琴:jsfiddle.net/fj10ruqs

标签: jquery navbar sticky


【解决方案1】:

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

【讨论】:

  • 谢谢,没注意到 :D
  • 现在我有另一个问题...如果导航栏点击默认dist,它应该回到原来的位置...jsfiddle.net/fj10ruqs/1
  • 好的,我想通了。无需更多帮助
  • 一旦导航栏被修复,你的distance变量将永远为零,所以它永远不会是&gt;= defaultNavDist。你没有仔细地走过你的逻辑。使用 F12 和 console.log 显示代码中不同位置的变量,您将能够找到错误,而不是依赖像我这样无聊的人。 :)
  • 是的,我知道,我昨天没睡好
【解决方案2】:

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

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");
  }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多