【问题标题】:how to remember previous page's scroll position when click back button单击后退按钮时如何记住上一页的滚动位置
【发布时间】:2021-04-04 23:18:34
【问题描述】:

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

还有this

我真的很想记住页面的滚动位置。

这是我的 css 代码,你能解决这个问题吗?

.contents_container {width: 100%; height: 100%; overflow-y: scroll; position: relative; float:left;}

谢谢。

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/25168861/…
  • 谢谢你,但它不起作用。
  • 你介意localStorage吗?
  • @sergeykuznetsov 你能解释一下吗?
  • 您的 snipped 代码存在一个问题,您没有将值从 cookie 解析为数字。

标签: javascript html jquery css


【解决方案1】:

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

【讨论】:

  • 谢谢,但它不起作用。我认为问题是“.contents_container”的“overflow-y:scroll”,但我想知道记住“.contents_container”中的滚动位置。
  • 所以,只要记住 container.scrollTop 在页面更改位置上的位置,然后。在页面加载时设置此位置。就像在这段代码中一样,但在 container.scrollTop 上更改 window.scroll。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
  • 2015-06-16
  • 1970-01-01
  • 2012-09-26
  • 2014-09-29
  • 2012-03-11
  • 2015-05-26
相关资源
最近更新 更多