2015-01-08 15 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; 
}); 
});