IE7中的window.location.hash问题

6
我们有一个JavaScript函数,应该使用锚点将页面“移动”到特定位置。这个函数只是使用window.location.href = "#" + hashName。这在Firefox中有效,但在IE中不起作用。我在Windows XP下使用IE7测试了这段代码。 我尝试过使用window.location.hrefwindow.location.hashwindow.location.replace以及所有这些方法,但是都使用document对象。 有人知道如何解决这个问题吗?

“使用文档对象”是什么意思?你应该像答案中建议的那样使用window.location,而不是document.location,因为后者只适用于Gecko引擎! - Christoph
我都用过了,但它们都不起作用。 - Vladimir Kadalashvili
弗拉基米尔,在IE7/XP上对我有效... - James
4个回答

6

IE和大多数其他浏览器可以使用anchor.focus()滚动到锚点,或者使用element.scrollIntoView(true)滚动到任何带有id的元素。


4

我刚在Vista的IE7中测试了这个,也许这个问题只存在于XP下的IE7?因为在IE7、Chrome和Firefox中我都没遇到问题:

 window.location.hash = hashName;

如果这个方法真的行不通,我们可以使用Kennebec建议的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>

2
你尝试过只改变location.hash吗?这可能会解决你的问题。
window.location.hash = "#" + hashName;

不熟悉这个。看起来不错,不过还需要测试一下... - Jonathan Fingland


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接