2015-01-08 17 views
1

假设有一个页面,如http://www.example.com/blahblah/#fragment。通过直接输入到地址栏,浏览器加载页面并自动跳转到#fragment锚点。打开带片段标识符的URL时,防止默认跳转?

有没有什么办法可以防止这种行为与JavaScript没有干预HTML代码?也许有一些事件在浏览器跳转到锚点之前触发?例如通过直接输入打开页面,点击链接后不跳转

此外,我寻找一种方式来防止跳跃,不让浏览器跳转,然后回滚。

+0

[修改document.location.hash无页滚动]的可能重复(http://stackoverflow.com/questions/1489624/modifying-document-location-hash-without-page-scrolling) –

回答

0

我想你应该遵循Modifying document.location.hash without page scrolling

对于简单的解决方案,你需要做一些小把戏,比如 - 预先准备一些文本的哈希值,使其不再引用现有的元素!

您可以从下面的代码片段中找到可能的提示,它是从以上链接的答案之一复制而来的。

$(function(){ 
//This emulates a click on the correct button on page load 
if(document.location.hash){ 
$("#buttons li a").removeClass('selected'); 
s=$(document.location.hash.replace("btn_","")).addClass('selected').attr("href").replace("javascript:",""); 
eval(s); 
} 

//Click a button to change the hash 
$("#buttons li a").click(function(){ 
     $("#buttons li a").removeClass('selected'); 
     $(this).addClass('selected'); 
     document.location.hash="btn_"+$(this).attr("id") 
     //return false; 
}); 
});