平滑滚动使用jquery

Smooth scroll using jquery

本文关键字:jquery 滚动 平滑      更新时间:2023-09-26

我有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;
            }
        }
    });
});

但是它不起作用。滚动并不平滑。

将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;
  }
}
});
});