javascript - 单击后退按钮时如何记住上一页的滚动位置
问题描述
有一些问题,导致滚动“contents_container”而不是滚动“body”。
从此以后,点击“history.back”忘记滚动位置。
我找到了 jquery cookie,但它不起作用。
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
这也是。
if (history.scrollRestoration === 'manual') {
history.scrollRestoration = 'auto';
}
这也是。
我真的很想记住页面的滚动位置。
这是我的css代码,你能解决这个问题吗?
.contents_container {width: 100%; height: 100%; overflow-y: scroll; position: relative; float:left;}
谢谢你。
解决方案
我是在 popstate 上完成的,即使在此事件页面上仍然存在但不可见,您也可以在 'beforeunload' 上实现这一点。(如果是服务器端渲染)
window.addEventListener('popstate', onLocationChange);
function onLocationChange(e){
const scrollY = window.scrollY || window.pageYOffset;
localStorage.setItem("scrollY", scrollY)
}
window.addEventListener("load", onPageLoad);
function onPageLoad(){
const scrollY = parseInt(localStorage.getItem("scrollY"));
if(scrollY && !isNaN(scrollY)) {
window.scrollTo(0, scrollY)
}
}
对于溢出的容器
window.addEventListener('popstate', onLocationChange);
function onLocationChange(e){
//if(document.location.test() or startsWith() ....
// to fire only on desired pages
const container document.querySelector('.contents_containe');
const scrollTop = container.scrollTop;
localStorage.setItem("container-scrollTop", scrollTop)
}
window.addEventListener("load", onPageLoad);
function onPageLoad(){
const scrollTop = parseInt(localStorage.getItem("container-scrollTop"));
if(scrollTop && !isNaN(scrollTop)) {
const container document.querySelector('.contents_containe');
container.scrollTop = scrollTop;
}
}
推荐阅读
- html - How do you select a random element out of list, in django template?
- angular - Unable to fetch ENV values from docker to Angular application
- shell - Assign jq command to a variable and process the variable in later variables
- python - Python 全局变量意外行为
- c++ - jwt-cpp library LNK2019 Unresolved external symbol
- ios - 2020 年 UIKit 还在使用 OpenGL 渲染吗?
- flutter - 在桌面屏幕上正确显示登录页面
- bash - Why do these two rm commands produce different outputs?
- julia - 对使用 MPI 的 Julia 代码进行基准测试的正确方法是什么?
- python - 如何在python中的字典中添加函数作为值?