我可以在不滚动网页的情况下更新 window.location.hash 吗?
使用JavaScript,有没有办法在不滚动网页的情况下更新window.location.hash?
我有可点击的标题元素,可以切换它们正下方的 div 的可见性。 我希望在单击标题时在历史记录中显示 /foo#bar,但不希望页面滚动。 因此,当离开 /foo#bar 时,我将能够使用后退按钮,并让 ID 位于 window.location.hash 中的 div 在返回时可见。
这种行为可能吗?
Using JavaScript, is there a way to update window.location.hash without scrolling the web page?
I have clickable title elements that toggle the visibility of a div directly beneath them. I want the /foo#bar in the history when clicking titles but don't want the page scrolling about. So when navigating away from /foo#bar I'll be able to use the back button and have the div whose ID is in window.location.hash be visible upon return.
Is this behavior possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要在不重新加载/滚动页面的情况下更改哈希值,您现在只需使用 html5
history.pushState
即可。所有主要浏览器均支持它:
http://caniuse.com/history
MDN:
https://developer.mozilla.org /en-US/docs/Web/Guide/API/DOM/Manipulated_the_browser_history#The_pushState().C2.A0method
另请注意,我们在这里使用的最后一个 url 参数可以是任何 url,因此它不限于哈希值。
To change the hash without having the page reload/scroll, you can now simply use html5
history.pushState
.It's supported by all the major browsers:
http://caniuse.com/history
MDN:
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method
Also note that the last url parameter we're using here can be any url, so it's not limited to hashes.
尽可能简单
As easy as it get
您可以尝试的另一件事是暂时更改哈希指向的元素的 id。 为我工作!
Another thing you could try is changing the id of the element the hash points to temporarily. Worked for me!
这种行为是很有可能的。 您应该研究一些为您提供此功能而开发的库。
非常简单的历史记录:http://code.google.com/p/reallysimplehistory/
SWFAddress: http://www.asual.com/swfaddress/
This behavior is very much possible. You should look into some of the libraries that have been developed to give you this functionality.
Really Simple History: http://code.google.com/p/reallysimplehistory/
SWFAddress: http://www.asual.com/swfaddress/
根据 Sunny 的回答,我创建了这个函数,它也避免了未定义和空值:
Based on the answer from Sunny I made this function that also avoids undefined and nulls:
想向凯瑟琳的答案添加评论,但我还没有代表 -
很好的解决方案,但它在 Chrome 中对我不起作用,因为 $('html').scrollTop() 总是返回 0 - 一个小的编辑解决了问题:
Wanted to add a comment to Catherines answer but I don't have the rep yet -
Great solution however it wasn't working for me in Chrome as $('html').scrollTop() always returns 0 - a minor edit resolves the issue: