Scrolling a page using location.hash in Safari

白昼怎懂夜的黑 提交于 2019-12-10 06:13:27

问题


I have a forum page that displays a tree view of messages below the currently selected message. When you click on a message in the tree the new message body is loaded into a div near the top of the page using AJAX and then the following code is run:

window.location.hash = "page_top";

Of course "page_top" is an anchor element near the top of the page, so the newly loaded message body scrolls into view.

This works fine on all the browsers, except Safari. On Safari (tested on PC and iPhone) it only works the first time you set location.hash. If you set it again the page does not scroll.

The end result is that the newly loaded message body does not scroll into view in Safari and you have to scroll back to the top of the page every time you pick a new message from the tree.

Why does Safari not like this and is there anything I can do to fix it ?

Edit:

I'm guessing this is related to a bug that you can find by Googling about location.hash and Safari. It seems Safari used to have a bug where if you set the hash to the same value twice it would cause it to reload the page. I'm guessing when they fixed that bug they fixed it a little too thoroughly and stopped it doing anything when you set hash to the same value again.

http://www.howtocreate.co.uk/safari/locationHashBug.html


回答1:


You could reset it first:

window.location.hash = "";
window.location.hash = "page_top";



回答2:


I needed to add:

<div><a name="page_top"></a></div>
<div><a name="page_topnot"></a></div>

Using "a name" instead of "a href". Works great!




回答3:


Answering my own question. Gumbo was on the right track, but not quite there.

Safari doesn't like location.hash being set to a blank value. Instead you need to set it to a real anchor value.

So along at the top of the page I now have:

<div><a href="page_top"></a></div>
<div><a href="page_topnot"></a></div>

I found that I needed the divs around the anchors otherwise Safari was scrolling to an unpredictable part of the page rather than to the anchors.

Then to scroll to the top of the page I have to do:

window.location.hash = "page_topnot";
window.location.hash = "page_top";

With that in place Safari will scroll to top of the page every time.




回答4:


I had the same problem as you had and this solution worked - the only thing I noticed was that in IE, I could hear two clicks - So I did a variation of yours and just put one anchor and it worked as well (ie, call twice, the first time, a non-existent anchor, the second time the real one)

On top, my anchor:

(tag a)name="top" id="top"(end of tag a)

Within javascript, the two calls:

window.location.hash ="topnot";

window.location.hash ="top";

Thanks for your help!



来源:https://stackoverflow.com/questions/549148/scrolling-a-page-using-location-hash-in-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!