实现页面元素滚动到容器底部的2中常用方案

方案1 让容器的滚动条top值等于容器的滚动条高度
containerEl.scrollTop = containerEl.scrollHeight

方案2 让元素的最后一项执行scrollIntoView(false)

具体见demo吧

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      .container {
        border: solid 1px #ccc;
        width: 200px;
        height: 200px;
        overflow-y: auto;
      }
    </style>
  </head>
  <body>
    <button id="btn1">to bottom 1</button>
    <button id="btn2">to bottom 2</button>
    <div class="container">
      <div class="item">first item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">item</div>
      <div class="item">last item</div>
    </div>
    <script>
      var containerEl = document.querySelector(".container")
      var btn1El = document.querySelector("#btn1")
      var btn2El = document.querySelector("#btn2")
      btn1El.addEventListener("click", function () {
        containerEl.scrollTop = containerEl.scrollHeight
      })
      btn2El.addEventListener("click", function () {
        let lastItemEl = document.querySelectorAll(".item")
        lastItemEl[lastItemEl.length - 1].scrollIntoView(false)
      })
    </script>
  </body>
</html>

 

本站文章如未注明均为原创 | 文章作者:刘晓帆 | 转载请注明来自:前端印象

发表评论

邮箱地址不会被公开。 必填项已用*标注

浏览量:22 次浏览