将动画切换到页面的不同部分

Swing animation to different parts of page

本文关键字:同部 动画      更新时间:2023-09-26

我正试图使用摆动动画将href应用到页面的某些部分。然而,我不确定该放什么来引用我的HTML的正确sections。我认为最好的办法是选择我的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:

<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>

工作演示:http://jsfiddle.net/p0tavns5/2/

$("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);
    });
})

来源:http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery

这也具有优雅退化的优点。如果它没有运行(noscript或其他什么),它将默认为常规片段链接。