簡體   English   中英

使用jQuery平滑滾動

[英]Smooth scroll using 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;
            }
        }
    });

});

但這是行不通的。 滾動不流暢。

用以下代碼替換您的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