jQuery 防止页面加载时的默认哈希行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3503559/
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
Prevent default hash behavior on page load
提问by bobsoap
I have a page with a tabbed interface. Each tab has a unique id. I've enabled links pointing to that page with the appended id after the hash, and I'm now trying to circumvent the default browser behavior that opens a URL with hash at the location of the element on the page.
我有一个带有选项卡式界面的页面。每个选项卡都有一个唯一的 ID。我已启用指向该页面的链接,并在哈希后附加 id,现在我试图规避默认浏览器行为,该行为在页面上元素的位置打开带有哈希的 URL。
So:
所以:
- pageA links to pageB like this:
<a href="pageB.php#Tab4">Go</a>
- pageB opens, and my jQuery activates the correct tab, but the browser has scrolled down to where
<div id="Tab4">
is located on the page.
- pageA 链接到 pageB,如下所示:
<a href="pageB.php#Tab4">Go</a>
- pageB 打开,我的 jQuery 激活了正确的选项卡,但浏览器已向下滚动到
<div id="Tab4">
页面上的位置。
That's exactly what I want to prevent.
这正是我想要防止的。
Any ideas? Thanks!
有任何想法吗?谢谢!
回答by Ian Wetherbee
There isn't a way to prevent the default hash behavior, but you can alter your hash scheme so the #tag doesn't correspond to any ID on your page. On page load, take the hash value and append a constant (ex: _hash
), then scroll to that using jQuery.
没有办法阻止默认的散列行为,但您可以更改散列方案,使 #tag 不对应于您页面上的任何 ID。在页面加载时,获取哈希值并附加一个常量(例如:)_hash
,然后使用 jQuery 滚动到该值。
Example: http://mysite/page.php#tab4
示例: http://mysite/page.php#tab4
page.php has <div id="tab4_hash"></div>
page.php 有 <div id="tab4_hash"></div>
On page load, get the div by doing tab4
+ _hash
在页面加载时,通过执行tab4
+获取 div_hash
回答by Frank Forte
I would use this:
我会用这个:
window.scrollTo(0,0);
This way you don't need to change element id's or anything else.
这样您就不需要更改元素 ID 或其他任何内容。
I came across the problem where I wanted to scroll down to the tab, but for some reason it scrolled past it to the bottom of the page (no, there was not a duplicate id). I think it is because the browser would scroll to the id before the content finished loading, and the extra content pushed the element above the new scroll position). I fixed it with this:
我遇到了我想向下滚动到选项卡的问题,但由于某种原因它滚动到页面底部(不,没有重复的 ID)。我认为这是因为浏览器会在内容加载完成之前滚动到 id,并且额外的内容将元素推到新的滚动位置上方)。我用这个修复了它:
if(document.location.hash)
{
window.location = document.location.hash;
}
the "if" statement here is mandatory or you might get an infinite loop
这里的“if”语句是强制性的,否则你可能会得到一个无限循环
回答by Mario Estrada
After you're done loading the right tab, run this:
完成加载正确的选项卡后,运行以下命令:
window.location = '#';
回答by Sergei Smirnov
- You should just hide the element with id=hash by default
- Аnd then, after the page loads, you make the element visible.
- 默认情况下,您应该使用 id=hash 隐藏元素
- 然后,在页面加载后,您使元素可见。
You can find more info here: How to disable anchor "jump" when loading a page?
您可以在此处找到更多信息:如何在加载页面时禁用锚点“跳转”?