2013-04-12 40 views
0

在我的主页上,我有一个带有ID的菜单,当我点击它时,它会滑动到相应的div并且它可以平滑运行。在URL中缓慢导航到ID

但是,当我不在我的主页上,我点击一个项目,我希望能够转到主页,然后滑动到该部分。

这是我现在使用的代码:

$('#mainMenu a').click(function(e){ 
    e.preventDefault(); 
    var div = $(this).attr('href'); 
    if('<?=get_site_url()?>/' == '<?=get_permalink()?>') 
    { 
     $('html, body').animate({scrollTop:$(div).position().top}, 'slow'); 
    } 
    else 
    { 
     window.location.href = '<?=get_site_url()?>/'+div; 
    } 
}); 

这个做工精良,下一部分工程,但我不能让它滑动到ID。

if (window.location.hash != "") { 
    e.preventDefault(); 
    $('html, body').animate({scrollTop:$(window.location.hash).position().top}, 'slow'); 
} 

有没有一种方法可以防止浏览器直接跳到该部分,而是滑动到它?

+0

http://stackoverflow.com/questions/3503559/prevent-default-hash-behavior-on-page -load – thefrontender

回答

0

这就像一个魅力:

$('#mainMenu a').click(function(e){ 
    e.preventDefault(); 
    var div = $(this).attr('href'); 
    if('<?=get_site_url()?>/' == '<?=get_permalink()?>') 
    { 
     $('html, body').animate({scrollTop:$(div).position().top}, 'slow'); 
    } 
    else 
    { 
     localStorage.setItem("hash", div); 
     window.location.href = '<?=get_site_url()?>/'; 
    } 
}); 

if (localStorage.getItem("hash")!=null) { 
    $('html, body').animate({scrollTop:$(localStorage.getItem("hash")).position().top}, 'slow'); 
    localStorage.removeItem("hash"); 
} 

而不是把散在我的网址我保存它的localStorage和我我检查,如果它被设置页面的头部。

成立该解决方案张贴问题仅仅几分钟后,感谢那些谁帮我:)

1

尝试滚动到在开始右上方,然后滚下来:

if (window.location.hash != "") { 
    $('html, body').scrollTop(0).animate({scrollTop:$(window.location.hash).position().top}, 'slow'); 
} 

此外,删除e.preventDefault(),因为你不能定义一个名为e,也不是一个event任何变量。

+0

感谢您的答案,e是在我的document.ready(功能(e){... 这工作,但不是真正平稳,有些闪烁,我找到了另一种方式,我会发布我的解决方案在分钟;) 无论如何,谢谢! –