且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单击浏览器后退按钮时,将用户带回上一页滚动到的位置

更新时间:2023-12-03 10:20:52

如果在页面加载"事件触发后加载内容,则后退按钮不会将您带回原来的位置.因为浏览器在 'load' 事件之前滚动.

If the content is loaded after page "load" event firing, then the back button would not take you back to the position you were. Because the browser scrolls before the 'load' event.

在这种情况下,为了让浏览器记住滚动位置,您必须在导航离开之前将滚动位置和状态(已加载的内容)存储在某处.无论是在 cookie 中,还是在 url 哈希中.

To make the browser remember the scroll position in this case, you have to store the scroll position and status (what content have been loaded) somewhere before navigating away. Either in the cookie, or in the url hash.

如果pageA只是一个没有动态内容的静态页面(在'load'事件之后加载,浏览器应该在你返回时记住滚动位置.

If pageA is just a static page without dynamic content (loaded after 'load' event, the browser should remember the scroll position when you go back.

对于动态内容,至少包括两部分.一种是在单击返回"按钮时恢复页面状态,因此所有动态内容都被加载,一些扩展器被展开或折叠.另一个是滚动到那里.

For dynamic content, there at least includes two parts. One is recovering the page status when click "Back" button, so all the dynamic content is loaded, some expander are expanded or collapsed. The other is scroll to there.

第一部分取决于页面的实现方式.第二部分您可以在页面执行 onUnload 时将滚动顶部放入 cookie.例如

The first part depends on how the page is implemented. The 2nd part you can put the scroll top into the cookie when page doing onUnload. For example

$(window).unload(function() {$.cookie('scrollTop',$(window).scrollTop());});