gpt4 book ai didi

javascript - 我可以在不滚动网页的情况下更新 window.location.hash 吗?

转载 作者:行者123 更新时间:2023-12-03 00:32:22 25 4
gpt4 key购买 nike

使用JavaScript,有没有一种方法可以在不滚动网页的情况下更新window.location.hash?

我有可点击的标题元素,可以切换它们正下方的 div 的可见性。我希望在单击标题时在历史记录中显示/foo#bar,但不希望页面滚动。因此,当离开/foo#bar 时,我将能够使用后退按钮,并让 ID 位于 window.location.hash 中的 div 在返回时可见。

这种行为可能吗?

最佳答案

要在不重新加载/滚动页面的情况下更改哈希值,您现在只需使用 html5 history.pushState

history.pushState(null,null,'#hashexample');

所有主流浏览器都支持:

http://caniuse.com/history

MDN:

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method

另请注意,我们在这里使用的最后一个 url 参数可以是任何 url,因此它不限于哈希值。

关于javascript - 我可以在不滚动网页的情况下更新 window.location.hash 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/645202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com