如何将 HTML ID 链接与 Bootstrap 导航栏标题一起使用?

sac*_*shu 3 html javascript jquery ruby-on-rails-3 twitter-bootstrap

在我的 rails 应用程序中,我试图构建一个简单的 FAQ 页面,该页面有一个侧边栏,当您单击某个主题时,它会向下移动到该问题。

所以我在侧边栏中的一段代码看起来像:

<li><a href="#work">How does it work?</a></li>
Run Code Online (Sandbox Code Playgroud)

然后我有一个匹配的 h2 与 id="work"。

当我测试它时,它一直在超调,我想是因为它显示了从页面最顶部开始的内容,该页面被 Bootstrap 中的导航栏隐藏。解决此问题的最佳方法是什么?

mer*_*erv 5

有同样的问题。这是我想出的:

// listen for click events originating from elements with href starting with #
$('body').on('click.scroll-adjust', '[href^="#"]', function (e) {
  var $nav

  // make sure navigation hasn't already been prevented
  if ( e && e.isDefaultPrevented() ) return

  // get a reference to the offending navbar
  $nav = $('div.navbar')

  // check if the navbar is fixed
  if ( $nav.css('position') !== "fixed" ) return

  // listen for when the browser performs the scroll
  $(window).one('scroll', function () {
    // scroll the window up by the height of the navbar
    window.scrollBy(0, -$nav.height())
  });

});
Run Code Online (Sandbox Code Playgroud)