简体   繁体   中英

How to remember scroll position of overflow:scroll div?

I have one container div what overflow-y:scroll.

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

I want to remember the container's scroll position when clicked back button or refresh.

So I got helped from stackoverflow, But I doesn't works.

Here is my script and could you fix the problem?

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.addEventListner("load", onPageLoad);

function onPageLoad(){
   const scrollTop = parseInt(localStorage.getItem("container-scrollTop"));
   if(scrollTop && !isNaN(scrollTop){
      const container document.querySelector('.contents_containe');
      container.scrollTop = scrollTop;
   } 
}

There are 2 things you want to do.

  1. Save current scroll position when you leave the page
  2. Jump to that position on page load

Saving current position:

window.addEventListener("beforeunload", () => {
  localStorage.setItem("scrollPositon", document.querySelector(".contents_container").scrollTop);
});

Retriving position:

window.addEventListner("load", () => {
  document.querySelector(".contents_container").scrollTop = localStorage.getItem("scrollPositon") || 0;
});

You might want to read up on the localStorage API

Let's take a closer look at the saving part: beforeunload

// event fires, if the user leaves the page
window.addEventListener("beforeunload", () => {
  // save an item to the users local storage
  localStorage.setItem(
    "scrollPositon", // item name/key
    document.querySelector(".contents_container").scrollTop // item value (scroll top position in this case)
  );
});

We then basically do the reverse when the page loads:

// event fires when the page loads
window.addEventListner("load", () => {
  // setting scrollTop of container to:
  document.querySelector(".contents_container").scrollTop = 
    // whatever value the item with name/key scrollPosition in the local storage holds
    localStorage.getItem("scrollPositon") || 0; // or if it's not set, simply use 0 as fallback
});

Edit: I haven't run your code, but I noticed an error. You're using document.querySelector('.contents_containe') in your JS but .contents_container {... } in the CSS. The JS version lacks the r at the end. Always make sure the selectors are the same across HTML/CSS/JS!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM