英文:
Stores the scroll offset on the page
问题
我正在尝试使用以下JavaScript代码来保持我的页面滚动位置:
document.body.addEventListener("load", function (event) {
var scrollpos = sessionStorage.getItem('scrollpos');
if (scrollpos) {
window.scrollTo(0, scrollpos);
sessionStorage.removeItem('scrollpos');
}
});
window.addEventListener("beforeunload", function (e) {
sessionStorage.setItem('scrollpos', window.scrollY);
});
但我已经尝试过了,但它不起作用,有什么问题?
英文:
I'm trying to maintain my page scroll offset with javascript with the code below:
document.body.addEventListener("load", function (event) {
var scrollpos = sessionStorage.getItem('scrollpos');
if (scrollpos) {
window.scrollTo(0, scrollpos);
sessionStorage.removeItem('scrollpos');
}
});
window.addEventListener("beforeunload", function (e) {
sessionStorage.setItem('scrollpos', window.scrollY);
});
And I've tried it but it's not working, what's wrong with it?
答案1
得分: 1
使用sessionStorage,当标签页关闭时,滚动位置值将被删除,因此在卸载页面之前保存sessionStorage将不起作用。
一个替代方法是使用localStorage。这个值不会过期,但如果你只想保存滚动位置一段时间,也可以存储卸载的时间和日期。可以这样做:
window.addEventListener("beforeunload", function (e) {
localStorage.setItem('scrollpos', window.scrollY);
const now = new Date();
localStorage.setItem('lastunload', now);
});
然后在加载页面时,你可以这样做:
document.body.addEventListener("load", function (event) {
var scrollpos = localStorage.getItem('scrollpos');
const now = new Date();
const then = localStorage.getItem('lastunload');
var diff = Math.abs(now - then) * 1000; // 获取以秒为单位的差值
if (scrollpos && diff < (10 * 60)) { // 检查是否已经过去了10分钟
window.scrollTo(0, scrollpos);
localStorage.removeItem('scrollpos');
}
});
希望这有所帮助!
英文:
Using sessionStorage, your scroll-position value is deleted as soon as the tab is closed, so saving sessionStorage before unloading a page would do nothing.
An alternative is to use localStorage. This value wouldn't expire, but if you want the scroll-position only to be saved for some time, you could also store the time and date of the unload. This could be done like this:
window.addEventListener("beforeunload", function (e) {
localStorage.setItem('scrollpos', window.scrollY);
const now = new Date();
localStorage.setItem('lastunload', now);
});
And then when loading the page you would do:
document.body.addEventListener("load", function (event) {
var scrollpos = localStorage.getItem('scrollpos');
const now = new Date();
const then = localStorage.getItem('lastunload');
var diff = Math.abs(now-then)*1000; //this gets the diff in seconds
if (scrollpos && diff<(10*60)) { //checks if it's been 10 minutes
window.scrollTo(0, scrollpos);
localStorage.removeItem('scrollpos');
}
});
Hope this helps!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论