单击"后退"按钮时如何记住上一页的滚动位置



出现一些问题,导致滚动"contents_container";而不是滚动";身体";。

从那时起,单击";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;
} 
}

最新更新