Javascript 当锚点在 URL 中时,避免页面滚动/跳跃
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10626814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Avoid the page scrolling/jumping when anchor is in the URL
提问by Ben
Possible Duplicate:
jquery - disable anchor “jump” when loading a page
可能的重复:
jquery - 加载页面时禁用锚点“跳转”
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.
我根据 URL 中的哈希值显示一个 div,但我想避免页面跳转到具有该特定 ID 的 div 的位置。
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.
我只有在使用 URL 中的散列直接导航页面时才会出现问题,例如,如果有人在书上标记了页面。
So for example I have the url domain.com/page.html#myitem-1
例如,我有 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.
ID=myitem-1 然后将显示,它会显示,但页面然后跳到我不想要的那个 div 的位置。
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
我试图使用 scrollTop(0) 强制窗口位置回到顶部,但似乎在锚点跳转发生之前调用它没有任何效果
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?
我能够让这个 scrollTop 工作的唯一方法是将它放在持续时间为 1 的 setTimeOut 中,但这似乎有点像黑客。还有其他建议吗?
Thanks
谢谢
B
乙
采纳答案by Majki
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 ;)
好吧,如果这是您使用锚点仅用于显示 div 的内部机制,您可以随时更改(或删除)“名称”属性,这样浏览器就不会直接找到它,也不会尝试滚动;)
Otherwise try How to disable anchor "jump" when loading a page?
否则尝试加载页面时如何禁用锚点“跳转”?