Avoid the page scrolling/jumping when anchor is in the URL [duplicate]

别等时光非礼了梦想. 提交于 2019-12-21 03:32:48

问题


Possible Duplicate:
jquery - disable anchor “jump” when loading a page

I'm displaying a div depending on the hash value in a URL but i want to avoid the page jumping to the postion of that div with that particular ID.

I only have the problem when the page is navigated direct with the hash in the URL so say for example if someone has book marked the page.

So for example I have the url domain.com/page.html#myitem-1

ID=myitem-1 will then display, which it does but the page then jumps down to the postion of that div which i don't want.

I was trying to use scrollTop(0) to force the window position back to the top but it seems as if this gets called before the anchor jump takes place to has no effect

Example code:

  $(document).ready(function() {
    $('.glossary-term').hide();
    $(window.location.hash).show();

    $(window).scrollTop(0);

});

The only way i was able to get this scrollTop to work was to place it in a setTimeOut with a duration of 1, but this seems like a bit of a hack. Any other suggestions?

Thanks

B


回答1:


Well, if it is your internal mechanism for using anchors just for displaying divs you can always change (or remove) the "name" attribute so the browser won't find it directly and won't try to scroll ;)

Otherwise try How to disable anchor "jump" when loading a page?



来源:https://stackoverflow.com/questions/10626814/avoid-the-page-scrolling-jumping-when-anchor-is-in-the-url

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