2009-06-01 41 views
6

我們有一個javascript函數應該使用錨將頁面「移動」到某個位置。這個功能只是window.location.href = "#" + hashName。這適用於FF,但不適用於IE。我在Windows XP下使用IE7測試了這個代碼。 我試過using window.location.hrefwindow.location.hash,window.location.replace和所有這些方法,但使用document對象。 有誰知道如何處理這個問題?IE7中的window.location.hash問題

+0

來到你是什麼意思與 '使用文檔對象' 的問題嗎?你應該按照答案中的建議使用`window.location` - document.location是Gecko特定的! – Christoph 2009-06-01 13:54:20

+0

我用過他們 - 他們不工作 – 2009-06-01 14:24:57

+0

弗拉基米爾,在IE7/XP中爲我工作... – James 2009-06-01 15:50:02

回答

6

IE和大多數其他瀏覽器將滾動到錨與anchor.focus(),或與用element.scrollIntoView(真)的ID的任何元素

2

您是否試過改變location.hash

window.location.hash = "#" + hashName; 
4

我justed在IE7 Vista下測試了這,也許這個問題只存在於XP下的IE7中?因爲這個工作正常,我在IE7,Chrome和Firefox:

window.location.hash = hashName; 

如果這真的不工作,那麼我們可以使用scrollIntoView作爲肯納貝克建議。

function scrollToAnchor(anchorName){ 
    //set the hash so people can bookmark 
    window.location.hash = anchorName; 
    //scroll the anchor into view 
    document.getElementsByName(anchorName)[0].scrollIntoView(true); 
} 

使用這樣的:

<script type='text/javascript'>scrollIToAnchor('foo');</script> 
<a name='foo'></a> 
<p>I will be scrolled into view</p>