2012-10-09 86 views
0

我使用這個代碼順利錨之間滾動頁面上的漸進增強jQuery的平滑滾動錨和更新瀏覽器的地址

$('a[href*=#]').click(function(e) { 
    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) { 
      $('.active').removeClass('active'); 
      $(this).parent().addClass('active'); 
      var targetOffset = $target.offset().top; 
      $('html,body') 
      .animate({ 
       scrollTop: targetOffset 
      }, 750); 
      e.preventDefault(); 
      //location.hash = $(this.hash); 
     } 
    } 
}); 

我的問題是,有沒有辦法來更新瀏覽器的URL像正常一樣,但仍然能夠順利滾動?如果我取消註釋最後一行,它會跳到錨點,然後做動畫。

回答

1

我剛剛解決它,因爲我張貼。發佈此信息以幫助他人。 基本上,我只是在完成動畫時使用回調來更新瀏覽器位置。

$('a[href*=#]').click(function(e) { 
    if (location.pathname.replace('/^\//','') == this.pathname.replace('/^\//','') 
     && location.hostname == this.hostname) { 
     var hash = this.hash; 
     var $target = $(this.hash); 
     $target = $target.length && $target 
      || $('[name=' + this.hash.slice(1) +']'); 
     if ($target.length) { 
      $('.active').removeClass('active'); 
      $(this).parent().addClass('active'); 
      var targetOffset = $target.offset().top; 
      $('html,body') 
      .animate({ 
       scrollTop: targetOffset 
      }, 750, function() { 
       location.hash = hash; 
      }); 
      e.preventDefault(); 

     } 
    }