2013-07-02 167 views
1

我正在使用函数来平滑滚动页面的子部分。防止指定锚上的默认值

代码所指

event.preventDefault(); 

-to防止页面跳转到被点击锚当顶部,但它也没有包括hashtag追加到所使用的搜索引擎优化的URL。

这是我正在使用的滚动功能。

<script type="text/javascript"> 
$('.secondaryNav a').click(function(event){ 
     event.preventDefault(); 
     //calculate destination place 
     var dest=0; 
     scrolling = false; 
     if($(this.hash).offset().top > $(document).height()-$(window).height()){ 
       dest=$(document).height()-$(window).height(); 

     }else{ 
       dest=$(this.hash).offset().top; 
     } 
     //go to destination 
     $('html,body').animate({scrollTop:dest}, 2000,'easeInOutCubic',function() { 
     }); 

    }); 
</script> 

回答

3

preventDefault将停止散列被添加到URL,但您可以自己添加它。

location.hash = this.hash; 

这将调用onhashchange和滚动浏览器的哈希值,所以一定要确保你把它的滚动完成后。

var hash = this.hash; 
$('html,body').animate({scrollTop:dest}, 2000,'easeInOutCubic',function() { 
    location.hash = hash; 
}); 

DEMO:http://jsfiddle.net/Sub7m/4/show/(在编辑:http://jsfiddle.net/Sub7m/4/

如果你的浏览器支持的话,你也可以使用history.replaceState({}, null, this.hash)到哈希添加到URL无需移动浏览器或调用onhashchange

DEMO:http://jsfiddle.net/Sub7m/5/show/(在编辑:http://jsfiddle.net/Sub7m/5/

+0

感谢您的解释。这将很好地工作。 – hyperdrive

+0

不客气:-) –