最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - location.hash only take effect once in chrome and safari - Stack Overflow

programmeradmin0浏览0评论

I use location.hash to scroll to somewhere in my page. It works fine when the location has no hash. But it does not work if the location already has the same hash value.

For example, location.hash = 'a'; scrolls to <div id="a"></div>. Now location.href will be like .html#a. And if location.hash = 'a'; is triggered again, the window will not scroll. This only take place in Chrome and Safari.

I found a solution at Scrolling a page using location.hash in Safari, but I don't want to add an unnecessary tag.

And I have also tried location.href = '#a'. That works fine but I'm afraid it will cause page reloading. Does anybody have better ideas?

I use location.hash to scroll to somewhere in my page. It works fine when the location has no hash. But it does not work if the location already has the same hash value.

For example, location.hash = 'a'; scrolls to <div id="a"></div>. Now location.href will be like http://www.example.com/test.html#a. And if location.hash = 'a'; is triggered again, the window will not scroll. This only take place in Chrome and Safari.

I found a solution at Scrolling a page using location.hash in Safari, but I don't want to add an unnecessary tag.

And I have also tried location.href = '#a'. That works fine but I'm afraid it will cause page reloading. Does anybody have better ideas?

Share Improve this question edited May 23, 2017 at 12:24 CommunityBot 11 silver badge asked Oct 20, 2011 at 5:12 sAILINGsAILING 3131 gold badge3 silver badges5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

Your best bet is to replace the hash temporarily with some value that you know does not exist on the page, and then reload the hash trying to be accessed.

location.hash = 'a';

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

setHash('a');

That should do the trick.

发布评论

评论列表(0)

  1. 暂无评论