window.location = #anchor doesn't work in IE

岁酱吖の 提交于 2019-11-28 10:33:49
Josh Stodola

I have this code in production and it works fine in IE7...

location.hash = "#top";

However, if you are just trying to scroll to the top, this ought to be a lot easier...

window.scrollTo(0, 0);

The location object is broken up into several properties - href is only one of them

Another one, hash, is what you're looking for.

top.location.hash = 'top';

You can also do this without using the location/href at all - just use scrollTo()

top.scrollTo( 0, 0 );
Joe Lapp

I also had a problem with windows.location.hash working in all browsers but IE7 and IE8 (at least on Vista). After much experimenting, I discovered that page redirection was breaking hash assignment.

An error will occur in IE7 or IE8 if you assign a value to windows.location.hash from within a page that was loaded as a result of redirection via the HTTP "Location" header.

After discovering this, I was able to find a fix elsewhere on StackOverflow (see here). The solution is to have the browser redirect via Javascript. Here I repost the solution from the other StackOverflow page:

<html>
<head>
    <meta http-equiv="refresh" content="0; url=__REDIRECT_LOCATION__">
    <script>window.location = "__REDIRECT_LOCATION__";</script>
</head>
</html>

This would explain why some people were having a problem with setting hash and some were not, but I do not know that the originator of the thread was redirecting.

I should also point out that I couldn't just use scrollTo() because my purpose was to remove the hash tag from the address bar without reloading the page, not to scroll.

location.href = location.href.split("#")[0] + "#top"

EDIT: to avoid the possibility of ever having two hashes.

You have to check for hash before appending it. I did it with this,

window.location = ((location.href).indexOf('#') == -1 ? location.href + "#top" : location.href);

window.location.href = '#top';

And if this doesn't work, try the full URL

window.location.href = 'http://domain.com/my.html#top';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!