定义

Element接口的scrollIntoView()方法会滚动元素的父容器,使被调用scrollIntoView()的元素对用户可见。

示例

<div id="container">
  <div class="item" draggable="true">Item 1</div>
  <div class="item" draggable="true">Item 2</div>
  <div class="item" draggable="true">Item 3</div>
  <div class="item" draggable="true">Item 4</div>
  <div class="item" draggable="true">Item 5</div>
  <div class="item" draggable="true">Item 6</div>
  <div class="item" draggable="true">Item 7</div>
  <div class="item" draggable="true">Item 8</div>
  <div class="item" draggable="true">Item 9</div>
  <div class="item" draggable="true">Item 10</div>
</div>
<button onclick="scrollToItem()">Scroll to Item 6</button>
function scrollToItem () {
  const index = 5;
  const container = document.getElementById('container');
  const items = container.getElementsByClassName('item');
  if (index >= 0 && index < items.length) {
    items[index].scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
}
Last Updated:
Contributors: pengrengui