Javascript 按下后退按钮时如何保留可滚动区域的滚动位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29203312/
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
How can I retain the scroll position of a scrollable area when pressing back button?
提问by user2335065
I have a long list of links inside a big scrollable div. Each time when a user click on a link then click the back button, it starts at the very top of the div. It is not user friendly to our users. Any ways to let the browser scroll to the previous position when pressing the back button?
我在一个大的可滚动 div 中有很长的链接列表。每次当用户单击链接然后单击后退按钮时,它都会从 div 的最顶部开始。它对我们的用户来说不是用户友好的。有什么方法可以让浏览器在按下后退按钮时滚动到上一个位置?
Thank you very much!
非常感谢!
回答by mohamedrias
During page unload, get the scroll position and store it in local storage. Then during page load, check local storage and set that scroll position. Assuming you have a div element with id element. In case it's for the page, please change the selector :)
在页面卸载期间,获取滚动位置并将其存储在本地存储中。然后在页面加载期间,检查本地存储并设置滚动位置。假设您有一个带有 id 的 div 元素element。如果是页面,请更改选择器:)
$(function() {
$(window).unload(function() {
var scrollPosition = $("div#element").scrollTop();
localStorage.setItem("scrollPosition", scrollPosition);
});
if(localStorage.scrollPosition) {
$("div#element").scrollTop(localStorage.getItem("scrollPosition"));
}
});
回答by Jondi
I think we should save scroll data per page, also we should use session storage instead of local storage since session storge effects only the current tab while local storage shared between all tabs and windows of the same origin
我认为我们应该每页保存滚动数据,我们也应该使用会话存储而不是本地存储,因为会话存储仅影响当前选项卡,而本地存储在所有选项卡和同一来源的窗口之间共享
$(function () {
var pathName = document.location.pathname;
window.onbeforeunload = function () {
var scrollPosition = $(document).scrollTop();
sessionStorage.setItem("scrollPosition_" + pathName, scrollPosition.toString());
}
if (sessionStorage["scrollPosition_" + pathName]) {
$(document).scrollTop(sessionStorage.getItem("scrollPosition_" + pathName));
}
});
回答by G Stokes
I had the same problem with a simple user interface consisting of a fixed menu div and a scrolling document div ("pxeMainDiv" in the code example below). The following solution worked for me in Chrome 47.0.2526.106 m and in Firefox 43.0.3. (My application is for use in-house and I did not need to cater for old versions of IE).
我在一个由固定菜单 div 和滚动文档 div(下面代码示例中的“pxeMainDiv”)组成的简单用户界面中遇到了同样的问题。以下解决方案在 Chrome 47.0.2526.106 m 和 Firefox 43.0.3 中对我有用。(我的应用程序供内部使用,我不需要迎合旧版本的 IE)。
$(document).ready(function(){
if (history.state) {
$("#pxeMainDiv").scrollTop(history.state.data);
}
$("#pxeMainDiv").scroll(function() {
var scrollPos = $("#pxeMainDiv").scrollTop();
var stateObj = { data: scrollPos };
history.replaceState(stateObj, "");
});
});
On the div scroll event, the scroll position of the div is stored in the state object inside the browser history object. Following a press of the Back button, on the document ready event, the scroll position of the div is restored to the value retrieved from the history.state object.
在 div 滚动事件上,div 的滚动位置存储在浏览器历史对象内的状态对象中。按下后退按钮后,在文档就绪事件中,div 的滚动位置恢复为从 history.state 对象检索到的值。
This solution should work for the reverse navigation of an arbitrarily long chain of links.
此解决方案应该适用于任意长链接链的反向导航。
Documentation here: https://developer.mozilla.org/en-US/docs/Web/API/History_API
这里的文档:https: //developer.mozilla.org/en-US/docs/Web/API/History_API
回答by bruno
When using window.history.back(), this is actually default browser functionality as user SD. has pointed out.
使用 时window.history.back(),这实际上是用户 SD 的默认浏览器功能。有指出。
On a site I am currently building, I wanted the logo of the company to backlink to the index page. Since jQuery 3, $(window).unload(function()should be rewritten to $(window).on('unload', function(). My code looks like this (using Kirby CMS' php syntax):
在我目前正在构建的网站上,我希望公司的徽标反向链接到索引页面。从 jQuery 3 开始,$(window).unload(function()应该重写为$(window).on('unload', function(). 我的代码看起来像这样(使用 Kirby CMS 的 php 语法):
<?php if ($page->template() == 'home'): ?>
<script>
$(function() {
$(window).on("unload", function() {
var scrollPosition = $(window).scrollTop();
localStorage.setItem("scrollPosition", scrollPosition);
});
if(localStorage.scrollPosition) {
$(window).scrollTop(localStorage.getItem("scrollPosition"));
}
});
</script>
回答by Saurin Dashadia
If a back button is kind of history back button window.history.back()Then what you are seeking for, is a default browser functionality. So you don't have to worry about it.
如果后退按钮是一种历史后退按钮window.history.back()那么您正在寻找的是默认浏览器功能。所以你不必担心。
If your back button actually point to some URL in your application via link or form, then you have to take care that manually.
如果您的后退按钮实际上通过链接或表单指向应用程序中的某个 URL,那么您必须手动处理。
For solution you may use cookies to store your page scroll value. Each time user scroll on your page, do save scroll value for that page to cookie. Extra work is applied to manual cookie management.
对于解决方案,您可以使用 cookie 来存储您的页面滚动值。每次用户在您的页面上滚动时,请将该页面的滚动值保存到 cookie。额外的工作应用于手动 cookie 管理。
window.onScroll = function(){
document.cookie="pageid=foo-"+window.scrollY+";";
}
This cookie value can be use to set scroll value of the page on page visit.
此 cookie 值可用于设置页面访问时页面的滚动值。
window.scroll(0,cookievalue);

