防止命名锚点的默认值

时间:2013-07-02 17:35:29

标签: javascript jquery

我正在使用一个功能来平滑滚动到我的页面的子部分。

代码需要 -

event.preventDefault(); 

- 防止页面在单击锚点时跳转到顶部,但它也不会将主题标签附加到用于seo的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>

1 个答案:

答案 0 :(得分:3)

preventDefault会停止将哈希添加到网址中,但您可以自行添加。

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)将哈希添加到网址,而无需移动浏览器或拨打onhashchange

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

相关问题