首页 > 解决方案 > 单击后退按钮时如何记住上一页的滚动位置

问题描述

有一些问题,导致滚动“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;}

谢谢你。

标签: javascripthtmljquerycss

解决方案


我是在 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;
   } 
}


推荐阅读