Javascript 将动画旋转到页面的不同部分

Javascript 将动画旋转到页面的不同部分,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试使用swing动画将href切换到页面的某些部分。但是,我不确定该放什么来引用我的HTML中正确的部分。我认为最好的办法是选择我的a标签所指的href id。我对新方法持开放态度 jQuery: $("li a").each(function() { $(this).on("click", function() { var mode = "swing"; $('html, body').animate({ scrollTo

我正在尝试使用swing动画将
href
切换到页面的某些部分。但是,我不确定该放什么来引用我的HTML中正确的
部分。我认为最好的办法是选择我的
a
标签所指的
href id
。我对新方法持开放态度

jQuery:

$("li a").each(function() {
    $(this).on("click", function() {
        var mode = "swing";
        $('html, body').animate({
            scrollTop: $(/*HERE*/).offset().top
        }, 750, mode);
    });
})
HTML:


关于 服务 文件夹 接触
工作演示:

资料来源:

这也有优雅降级的优点。如果它不运行(noscript或其他),它将默认为常规片段链接

<div class="container">
  <nav class="navbar navbar-default navbar-fixed-top">
    <ul id="nav_pills" class="nav nav-pills" role="tablist">
      <li role="presentation">
        <a href="#about">About</a>
      </li>
      <li role="presentation">
        <a id="test" href="#services">Services</a>
      </li>
      <li role="presentation">
        <a href="#portfolio">Portfolio</a>
      </li>
      <li role="presentation">
        <a href="#contact">Contact</a>
      </li>
    </ul>
  </nav>
</div>

<!-- about -->
<section id="about">
  <div class="border">
    ABOUT
  </div>
</section>

<!-- services -->
<section id="services">
  <div class="border">
    SERVICES
  </div>
</section>

<!-- portfolio -->
<section id="portfolio">
  <div class="border">
    PORTFOLIO
  </div>
</section>

<!-- contact -->
<section id="contact">
  <div class="border">
    CONTACT
  </div>
</section>
$("li a").each(function() { // $('a[href^="#"]') might be a safer selector
    $(this).on("click", function(e) {
        var mode = "swing";
        e.preventDefault(); //stop the default jump to fragment
        $('html, body').animate({
            scrollTop: $(this.hash).offset().top // .hash is the element's href
        }, 750, mode);
    });
})