scrollIntoView:平滑滚动到指定位置

151 阅读1分钟
<body>
  <button id="btn">滚动</button>
  <div id="box" style="height: 300px;overflow: auto;"></div>
  <script>
    function elFormErrorScrollIntoView(tag) {
      // 获取第一个校验错误的元素
      const element = document.querySelectorAll(tag)[0];
      // 滚动到错误元素对应位置
      element.scrollIntoView({
        behavior: "smooth",
        block: "center"
      });
    }

    for (let i = 0; i < 100; i++) {
      const div = document.createElement('div')
      div.innerText = i
      div.className = 'div'
      document.getElementById('box').appendChild(div)
    }

    document.getElementById('btn').onclick = function () {
      elFormErrorScrollIntoView('.div')
    }
  </script>
</body>

动画.gif