scrollIntoView实现页面刷新自动滚动到上次浏览的位置

187 阅读1分钟

scrollIntoView()方法的介绍

scrollIntoView() 方法会滚动元素的父容器,也就是说滚动父容器直到位置父容器处于调用scrollIntoView()方法的容器的位置。

element.scrollIntoView(); // 等同于 element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean 型参数
element.scrollIntoView(scrollIntoViewOptions); // Object 型参数

常见的参数及其含义

1.element.scrollIntoView(true)

当参数为true时,elment的顶部对齐到可见区域的顶部,相当于scrollIntoViewOptions: {block: "start", inline: "nearest"}。这是默认值。

当参数为false时,elment的底部对齐到可见区域的底部,相当于scrollIntoViewOptions: {block: "end", inline: "nearest"}。这是默认值。

2.scrollIntoViewOptions的其他参数

behavior:(可选)定义过渡动画。"auto","instant"或"smooth"。默认为"auto"。
block:(可选)"start","center","end"或"nearest"。默认为"center"。
inline:(可选)"start","center","end"或"nearest"。默认为"nearest"。

点击实现平滑滑动

  var checkClose1 = document.querySelector("#checkClose1");

  var container8 = document.querySelector("#container8");
  checkClose3.addEventListener("click", () => {
    clearInterval(timer);
    window.setTimeout(() => {
      container8.scrollIntoView({ behavior: "smooth" });
    },100);
  });