将动画摆动到页面的不同部分

时间:2014-11-13 17:24:56

标签: javascript jquery html

我正在尝试使用摆动动画href到我页面的某些部分。但是我不确定要引用我的HTML的正确sections。我认为最好的办法是选择href id标记所指的a。我对新方法持开放态度

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>

1 个答案:

答案 0 :(得分:1)

工作演示: 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或其他东西),它将默认为常规片段链接。