jQuery Smooth Scroll锚点并更新浏览器位置

我正在使用此代码在页面上的锚点之间平滑滚动作为渐进增强

$('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,但仍然可以顺利滚动? 如果我取消注释最后一行,它将跳转到锚点,然后执行动画。

我发布的时候就解决了。 发布此内容以帮助他人。 基本上,我只是在完成动画时使用回调来更新浏览器位置。

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