2012-10-09 53 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(); 

     } 
    }