[英]how to remember previous page's scroll position when click back button
There were some problems, led to scrolling "contents_container" instead of scrolling "body".有一些问题,导致滚动“contents_container”而不是滚动“body”。
From then on, click "history.back" to forget the scroll position.从此,点击“history.back”忘记滚动position。
I found jquery cookie but it doesn't works.我找到了 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() );
});
});
and this too.这也是。
if (history.scrollRestoration === 'manual') {
history.scrollRestoration = 'auto';
}
I really want to remember the page's scroll position.我真的很想记住页面的滚动 position。
Here is my css code and could you fix the problem?这是我的 css 代码,你能解决这个问题吗?
.contents_container {width: 100%; height: 100%; overflow-y: scroll; position: relative; float:left;}
Thank you.谢谢你。
I made it on popstate, you can achieve this on 'beforeunload' even on this event page still exist but is not visible.我是在 popstate 上完成的,即使在此事件页面上仍然存在但不可见,您也可以在 'beforeunload' 上实现这一点。 (if is server side rendered) (如果是服务器端渲染)
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)
}
}
for overflowded container对于溢出的容器
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.