使用jquery平滑滚动

时间:2016-09-27 20:42:32

标签: javascript jquery

我有html页面和菜单

菜单:

<div id="sidebar-wrapper">
    <ul class="sidebar-nav">
       <li>
          <a href="#info">info</a>
       </li>
         ...
    </ul>
</div>

部分内容:

<div id="info" class="row">
     <div class="col-lg-12">
          <h1>Title</h1>
          <p>Lorem Ipsum</p>       
     </div>
</div>

我希望将平滑页面滚动添加到锚点。所以我试过了:

$(document).ready(function($) {

    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });

});

但它不起作用。并且滚动不顺畅。

1 个答案:

答案 0 :(得分:1)

用这个替换你的jQuery函数:

$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html, body').animate({
      scrollTop: target.offset().top
    }, 1000);
    return false;
  }
}
});
});
相关问题