如何导航到略高于锚标记?

Cam*_*ate 6 navigation anchor jquery ruby-on-rails twitter-bootstrap

我知道如何导航到页面上的给定锚标记 - 我要做的是链接到目标锚点上方30-40像素的页面的一部分.这样做的原因是我有一个引导程序导航,如果我喜欢直接使用锚点的页面部分,最终会覆盖部分相关内容.

目前我有这个链接:

%a{:href => root_path + "#how_it_works"} How It Works
Run Code Online (Sandbox Code Playgroud)

并在页面上链接到:

.span12#how_it_works
Run Code Online (Sandbox Code Playgroud)

有关如何获取链接导航到略高于.span12#how_it_works的页面部分的任何想法?

Nic*_*lin 1

你也许可以通过在 css 中添加一些额外的填充来解决这个问题,但最可靠的方法是使用 javascript:

$('a[href="#how_it_works"]').on('click',function(e){
  // prevent normal scrolling action
  e.preventDefault();
  // grab the target url from the anchor's ``href``
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
     if (target.length) {
           window.scrollTo(0, target.offset().top - 50); // <-- our offset in px adjust as necessary
      return false;
  }
});
Run Code Online (Sandbox Code Playgroud)

这是codepen

这使用了 Chris Coyier 的平滑滚动脚本的修改版本。我已经从滚动中去除了“平滑度”,但是您可以通过像这样设置滚动顶部动画来将其添加回来:

   if (target.length) {
     $('html,body').animate({
         scrollTop: target.offset().top + 20
    }, 1000);
    return false;
   }
Run Code Online (Sandbox Code Playgroud)