Element:scrollIntoViewIfNeeded() 方法

非标准: 该特性是非标准的,请尽量不要在生产环境中使用它!

Element.scrollIntoViewIfNeeded() 方法将不在浏览器窗口的可见区域内的元素滚动到浏览器窗口的可见区域。如果该元素已经在浏览器窗口的可见区域内,则不会发生滚动。此方法是标准的 Element.scrollIntoView() 方法的专有变体。

语法

js
scrollIntoViewIfNeeded()
scrollIntoViewIfNeeded(centerIfNeeded)

参数

centerIfNeeded 可选

一个可选的布尔值,默认为true

  • 如果为 true,则元素将在其所在滚动区的可视区域中居中对齐。
  • 如果为 false,则元素将与其所在滚动区的可视区域最近的边缘对齐。根据可见区域最靠近元素的哪个边缘,元素的顶部将与可见区域的顶部边缘对准,或者元素的底部边缘将与可见区域的底部边缘对准。

返回值

无(undefined)。

示例

js
const element = document.getElementById("my-el");

element.scrollIntoViewIfNeeded(); // 将元素置于可见区域的中心
element.scrollIntoViewIfNeeded(false); // 将元素与可见区域中最近的边缘对齐

规范

不属于任何规范。这是一种 WebKit 专有的方法。

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
scrollIntoViewIfNeeded
Non-standard

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Non-standard. Check cross-browser support before using.
See implementation notes.

参见