2011-05-04 69 views
4

想象一下,有人在他的瀏覽器地址欄中鍵入http://example.com/somepage#someanchor。 我怎麼能攔截這個調用錨點,正常顯示頁面(不要滾動到錨點),並在javascript中做一些事情,如警告'someanchor'。所有在js中,沒有服務器端重定向(像somepage?anchor = someanchor)。在javascript中攔截命名錨點

任何想法?這可能嗎?攔截點擊到錨點很容易,我控制,但這不是這種情況。

回答

4

攔截很容易(從onload處理器召本):

function getHash() { 
    var hash = window.location.hash; 
    return hash.substring(1); // remove # 
} 

爲了阻止窗口向下滾動到所述錨定器,你可能有上翻上onload事件。

+1

爲了完整性這個就說明be window.scrollTo(0,0); – Jan 2011-05-04 01:10:24

2

可以使用這樣做:

$(window).on('hashchange', function() { 
    //prevent default, then your code 
}); 

在本SO answer