點擊按鈕,讓頁面滾動到指定位置的方法

1.喵點

2.ele.scrollIntoView()

關於scrollIntoView方法:

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    ul {
      margin: 20px 0;
    }

    .item-style {
      height: 200px;
      margin: 20px 0;
      list-style: none;
      border: 1px solid #d6d6d6;
      font-size: 90px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .item-style:nth-child(2n) {
      background-color: cornflowerblue;
    }

    .item-style:nth-child(2n+1) {
      background-color: burlywood;
    }

    #input-style {
      width: 100%;
      height: 50px;
      font-size: 40px;
    }

    .btn-style {
      height: 60px;
      border-radius: 4px;
      border: none;
      background-color: darkcyan;
      font-size: 30px;
      color: #fff;
      margin: 20px;
    }
  </style>
</head>
<body>
<button onclick="moveCenter()" class="btn-style">
  測試scrollIntoViewIfNeeded---true
</button>
<button onclick="moveOther()" class="btn-style">
  測試scrollIntoViewIfNeeded---false
</button>
<button onclick="moveScrollIntoView(true)" class="btn-style">
  測試scrollIntoView--true
</button>
<button onclick="moveScrollIntoView(false)" class="btn-style">
  測試scrollIntoView--false
</button>
<button onclick="moveScrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'})"
        class="btn-style">
  測試scrollIntoView--動畫
</button>
<ul>
  <li class="item-style">
    1
  </li>
  <li class="item-style">
    2
  </li>
  <li class="item-style">
    3
  </li>
  <li class="item-style">
    4
  </li>
  <input type="text" placeholder="請輸入" id="input-style" />
  <li class="item-style">
    5
  </li>
  <li class="item-style">
    6
  </li>
  <li class="item-style">
    7
  </li>
  <li class="item-style">
    8
  </li>
</ul>
<script>
  var ele = document.getElementById('input-style')

  // 測試元素將在其所在滾動區的可視區域中居中對齊
  function moveCenter() {
    setTimeout(() => {
        ele.scrollIntoViewIfNeeded()
      },
      500)
  }

  // 測試元素將與其所在滾動區的可視區域最近的邊緣對齊
  function moveOther() {
    setTimeout(() => {
        ele.scrollIntoViewIfNeeded(false)
      },
      500)
  }

  // 測試scrollIntoView, 根據可見區域最靠近元素的哪個邊緣,
  //元素的頂部將與可見區域的頂部邊緣對準,或者元素的底部邊緣將與可見區域的底部邊緣對準。
  function moveScrollIntoView(content) {
    setTimeout(() => {
        ele.scrollIntoView(content)
      },
      500)
  }
</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章