Twitter的Bootstrap固定顶部导航栏滚动,页面内的锚链接弹跳

时间:2016-05-19 09:06:45

标签: javascript jquery html css twitter-bootstrap

我有一个带有顶部水平导航栏的网页 - 它是Twitter的Bootstrap Fixed Top Navbar更精确 - 具有底部固定位置(实际上它并没有真正由CSS修复;请参阅下面的JavaScript),因此导航栏将首先显示在页面底部,稍后在滚动时显示在页面顶部(position: fixed; top: 0)。

我的导航链接设置了锚标记,可以将查看器带到页面正文中的各个位置。不幸的是,有时它会让用户走得太远(特别是如果用户位于页面顶部并且导航栏尚未修复)。

看看我的HTML结构:

<div id="landing"></div>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li><a href="#landing">Home</a></li>
        <li><a href="#section1">Section 1</a></li>
        <li><a href="#section2">Section 2</a></li>
        <li><a href="#section3">Section 3</a></li>
      </ul>
    </div>
  </div>
</nav>
<div id="section1"></div>
<div id="section2"></div>
<div id="section3"></div>

我使用以下JavaScript确保导航栏在向下滚动后粘到页面顶部:

function init() {
  nh = 50; // navbar height
  sh = $(window).height();
  ih = sh-nh;            
  $("#landing").css('height', ih+'px');
} 

function navbarState() {
  if ($(window).scrollTop() > ih) {
        $('.navbar').addClass('navbar-fixed-top');
      } else {
        $('.navbar').removeClass('navbar-fixed-top');
      }
}

init();
navbarState();

$(window).on('load scroll resize orientationchange', function () {
    init();
    navbarState();
});

可以观察到,反复按压第一锚链会导致弹跳效果。我该如何防止这种情况?

我的目标是让导航滚动到正确的锚点,无论用户是否在目标网页上。

1 个答案:

答案 0 :(得分:0)

为什么不同时使用navbar-fixed-bottom

见这里:https://jsfiddle.net/y7soL4ej/

我将提到的类默认添加到nav。并修改了一些小事:

<强> CSS

html, body, div#landing {
  height: 100%
}
section, [id*=section] {
  padding-top: 52px;
}

JS

function init() {
  nh = 50 + 2; // navbar height + 2x border width (top + bottom)
  sh = $(window).height();
  ih = sh-nh;            
  //$("#landing").css('height', ih+'px');
}

function navbarState() {
  if ($(window).scrollTop() > ih) {
        $('.navbar').removeClass('navbar-fixed-bottom').addClass('navbar-fixed-top');
      } else {
        $('.navbar').removeClass('navbar-fixed-top').addClass('navbar-fixed-bottom');
      }
}

init();
navbarState();

$(window).on('load scroll resize orientationchange', function () {
    init();
    navbarState();
});

跳跃行为:当示例中导航栏位于底部时,它是dom流程的一部分 - 它将登陆 div和 section1 div分隔开来高度。一旦点击它,浏览器跳转到该位置,然后导航栏被设置为固定在顶部 - 并且不再是流的一部分(两个div不再被它分开)。因此,部分 div会相应地移动到 landing div,从而缩小差距。因此,再次点击相同的部分锚点会导致额外的跳转,因为由于登陆 div从position:static转到position:fixed,该部分已重新定位。

这是我建议使用navbar-fixed-bottom的另一个原因。

<强> 更新

新小提琴:https://jsfiddle.net/y7soL4ej/2/

我从HTML和JS中删除了.navbar-fixed-bottom,因为导航栏不应该从下到上跳转。 为了使其平滑并避免前面提到的跳跃行为,我不得不将其设置为绝对位置。

需要添加一些 CSS

div#landing {
  padding-bottom: 72px;
  margin-bottom: -72px;
}

nav.navbar {
  position: absolute;
  left: 0; right: 0;
}
nav.navbar.navbar-fixed-top {
  position: fixed;
}