有没有办法覆盖浏览器单击哈希值的默认行为?
当我有以下内容时:
<a name='test'></a>
...并将其加载到浏览器中,我可以将 #test
附加到 URL,浏览器将滚动,以便 位于页面顶部。
但是,我想更改此行为(如果可能的话使用 JavaScript),以便使用哈希不会滚动页面 - 我希望它什么也不做。
有没有办法在不删除 元素的情况下实现这一点?
更新:我需要浏览器仍然发送 onhashchange()
事件,但不滚动到 元素。原因是我想在保留事件通知的同时覆盖滚动。
When I have the following:
<a name='test'></a>
...and load it in a browser, I can append #test
to the URL and the browser will scroll so that the <a>
is at the top of the page.
However, I would like to change this behavior (using JavaScript if possible) so that using the hash does not scroll the page - I'd like it to simply do nothing.
Is there a way to do that without removing the <a>
element?
Update: I need the browser to still send onhashchange()
events but without scrolling to the <a>
element. The reason being that I want to override the scrolling while retaining the event notification.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一个快速的肮脏黑客,但它是您可以构建的东西:
我在这里使用 jQuery 使其跨浏览器工作并保持页面的 onhashchange 和 onscroll 处理程序完好无损。我发现的一个问题是,如果您单击同一个主题标签两次,它无论如何都会滚动。
UPD。我刚刚找到了一个更好的解决方案:
A quick dirty hack, but it's something you can build upon:
I used jQuery here to make it work across browsers and keep the page's onhashchange and onscroll handlers intact. One problem I spotted is that if you click the same hashtag twice it scrolls anyway.
UPD. I just figured out a better solution:
好吧,你可以尝试变得更残酷:
它必须在 DOM 准备好之后、渲染之前运行,所以你必须将它放在正确的位置。它不适用于“id”属性 - 仅适用于
它能达到你想要的效果吗?
Well, you can try to be brutal:
It has to be run after the DOM is ready but before it gets rendered so you have to put it in the right place. It won't work for 'id' attributes - only with <a name=...>
Does it do what you want?
试试这个:
Try this:
一种 hacky 技术是,如果 url 中存在哈希值,则自动滚动到页面顶部:
A kind-of hacky technique would be to just automatically scroll to the top of the page if there's a hash in the url:
也许您需要使用一些jquery和字符串操作
,或者找到带有散列的元素并从这些元素中删除名称散列属性。
perhaps you need to use a bit of jquery and string manipulation
Or find the elements with the hash and remove the name hash attributes from those elements.