1

我有一个最初不固定在顶部的导航栏,我在这里尝试做的是,当我滚动偏移量为 150 像素时,导航栏以固定位置固定在顶部,它使用页面内锚链接到页面的不同部分,顶部固定的词缀导航栏将突出显示页面锚区域中的正确(scrollspy?)

我的问题是,在导航栏固定到顶部后,固定导航栏会阻止锚点指向页面上的正确位置,因为某些内容隐藏在导航栏后面。

我已经对这个问题进行了相当长的研究,并看到了很多关于向 body 添加 padding-top 的建议,但同样,top-nav 直到通过滚动触发后才会修复。向正文添加填充后,导航仍然无法正确突出显示

我已经尝试了以下部分的解决方案 如何在 Bootstrap 中设置 ScrollSpy 的偏移量?

我不擅长解释,所以我将在这里发布一些屏幕截图。

这是滚动和附加之前的屏幕截图 在此处输入图像描述

这是导航栏固定到顶部后的屏幕截图,我滚动到页面内容 贴上固定顶部导航后的问题

我希望它如何工作 在此处输入图像描述

下面是我的代码。

<body data-spy="scroll">
  <!--This is the nav bar getting affixed to the top-->
  <div class="navbar navbar-custom navbar-inverse navbar-static-top" id="nav">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav nav-justified">
        <li><a href="#section1">About</a></li>
        <li><a href="#section2">Method</a></li>
        <li><a href="#section3">Findings</a></li>
        <li><a href="#section4">Final</a></li>
      </ul>
    </div><!--/.nav-collapse -->
  </div><!--/.navbar -->

这是内容区

<div class="mainContent">
  <div class="row">
    <div class="col-lg-7 col-md-7">
      <div id="section1">
        <h3>About the Project</h3>
      </div>
      <h4>Read the <a href="./assets/Preliminary_Avvo.pdf">Preliminary Proposal</a></h4>
    </div>

其余的 html 只是包含在 section2、section3 和 section4 中的内容

我的 CSS

.navbar-custom {
  border:none;
  background-color: #FFFFFF;
  font-weight:600;
  text-transform:uppercase;
  border-width:0;
}
.navbar-custom li{
  float:none;
}
.navbar-custom  .navbar-nav>li>a {
  color: #ddd;
}
.navbar-custom  .navbar-nav li>a:hover, .navbar-nav li .open, .navbar-custom     .navbar-nav .active a  {
  background-color:#902c00;
  color:#FFFFFF !important;
}
#nav {
  width: 100%;
  position:static;
  top:-32px;
}
#nav.affix {
  position: fixed;
  top: 0;
  z-index:10;
  width:940px;
}

JS

/* affix the navbar after scroll below header */
$('#nav').affix({
  offset: {
    top: 150
  }
});

/* highlight the top nav as scrolling occurs */
$('body').scrollspy({ target: '#nav' })
4

2 回答 2

2

这是一个代码片段,可防止您产生影响:

var navOffset = parseInt($('body').css('padding-top'));
$('body').scrollspy({ target: '#affix-nav', offset: navOffset+10 });
$('.navbar a').click(function (event) {
  var scrollPos = jQuery('body').find($(this).attr('href')).offset().top - navOffset;
  $('body,html').animate({ scrollTop: scrollPos}, 500, function () {});
  return false;
});

代码来自效果起作用的这个页面。

于 2014-06-02T19:38:39.160 回答
1

解决了。即使快速修复但有效,

window.addEventListener("hashchange", function() { scrollBy(0, -50) })

归功于这个家伙:https ://github.com/henrik

于 2014-10-07T12:21:17.977 回答