简体   繁体   English

刷新页面时保存侧边栏中的滚动位置

[英]Save the scroll position in sideBar when refreshing the page

I want to keep the scroll position in the sidebar, but I can't figure out what the error is.我想将滚动位置保留在侧边栏中,但我无法弄清楚错误是什么。 What did I do wrong in the JS script?我在 JS 脚本中做错了什么?

HTML: HTML:

<div class="sidebar">
    <div class="sidebarHeader">
        <h4 class="courseHeader"></h4>
    </div>
    <div class="sidebarMain">
        <ul class="sidebarUl">
            <li class="sidebarLi">
                <a class = "sidebarA" href="1.2.html">1.2</a>
            </li>
            <li class="sidebarLi">
                <a class = "sidebarA" href="2.1.html">2.1</a>
            </li>
        </ul>
    </div>
</div>

JS: JS:

document.querySelectorAll(".sidebarA", function() {
var sidebar = document.querySelector(".sidebar");

sidebar.scroll(0, localStorage.getItem('scrollPosition')|0);


sidebar.scroll(function () {
       localStorage.setItem('scrollPosition', sidebar.scrollTop)
});});

Element#scroll does not take a function as argument so you are never saving the new position anywhere. Element#scroll不将函数作为参数,因此您永远不会在任何地方保存新位置。

What you want to do instead is to listen for the scroll event:你想要做的是监听滚动事件:

sidebar.addEventListener('scroll', function() {
  console.log(sidebar.scrollTop);
});

Another thing:另一件事:

Element#querySelectorAll doesn't take a function as argument either; Element#querySelectorAll也不将函数作为参数; so所以

document.querySelectorAll(".sidebarA", function() { /* Stuff */ });

won't run the function you put there as a callback.不会运行您作为回调放在那里的函数。 If the goal is to run the code inside that function after the page has loaded, you can use the load event:如果目标是在页面加载后在该函数中运行代码,则可以使用 load 事件:

window.addEventListener('load', function() {
  var sidebar // and so on...
});

here is some change in your js code, be sure that sidebarUl class must look like这是您的 js 代码中的一些更改,请确保sidebarUl类必须看起来像

.sidebarUl {
  overflow-y: scroll;
  height: 100vh;
  width: 100px;
}

and parent element has css prop overflow:hidden并且父元素有 css prop overflow:hidden

const element = document.getElementsByClassName('sidebarUl')[0]
console.log('element', element)
element.addEventListener("scroll", function(e) {
  console.log('e', e.target.scrollTop);
  localStorage.setItem('scrollPosition', e.target.scrollTop)
});

window.onload = function() {
  const element = document.getElementsByClassName('sidebarUl')[0]
  var reloading = sessionStorage.getItem("scrollPosition");
  if (reloading != 0) {
    element.scroll(0, localStorage.getItem('scrollPosition')|0);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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