2011-10-20 45 views
6

我使用location.hash滾動到我的頁面中的某個位置。當該位置沒有散列時它工作正常。但是如果該位置已經具有相同的散列值,則不起作用。例如,滾動到<div id="a"></div>。現在location.href將會像http://www.example.com/test.html#a。如果再次觸發location.hash = 'a';,則窗口不會滾動。這隻發生在Chrome和Safari中。location.hash只在鍍鉻和Safari瀏覽器中生效一次

我在Scrolling a page using location.hash in Safari找到了解決方案,但我不想添加不必要的標籤。我也試過location.href = '#a'。這工作正常,但恐怕會導致頁面重新加載。有人有更好的想法嗎?

回答

14

最好的辦法是暫時用一些你知道不存在的值替換哈希值,然後重新加載試圖訪問的哈希值。

location.hash = 'a'; 

// this is the function that changes the hash 
function setHash(newHash) { 
    location.hash = 'someHashThatDoesntExist'; 
    location.hash = newHash; 
} 

setHash('a'); 

這應該做的伎倆。

相關問題