简体   繁体   English

使用jQuery平滑滚动

[英]Smooth scroll using jquery

I have html page and menu 我有html页面和菜单

Menu : 菜单:

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

Part of content : 部分内容:

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

And I want to add smooth page scroll to an anchor. 我想将平滑的页面滚动添加到锚点。 So I tried: 所以我尝试了:

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

});

But it doesn't work. 但这是行不通的。 And scroll isn't smooth. 滚动不流畅。

Replace your jQuery function with this: 用以下代码替换您的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;
  }
}
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM