元素:scrollIntoView() 方法
Baseline 广泛可用 *
Element 接口的 scrollIntoView() 方法滚动元素的祖先容器,使调用 scrollIntoView() 的元素对用户可见。
语法
js
scrollIntoView()
scrollIntoView(alignToTop)
scrollIntoView(options)
参数
alignToTop可选-
一个布尔值。
- 如果为
true,元素的顶部将与可滚动祖先的可见区域的顶部对齐。相当于scrollIntoViewOptions: {block: "start", inline: "nearest"}。这是默认值。 - 如果为
false,元素的底部将与可滚动祖先的可见区域的底部对齐。相当于scrollIntoViewOptions: {block: "end", inline: "nearest"}。
- 如果为
options可选-
具有以下属性的对象:
behavior可选-
确定滚动是即时发生还是平滑动画。其值可以是以下之一:
smooth:滚动应该平滑动画。instant:滚动应该即时发生,一次性跳转。auto:滚动行为由scroll-behavior的计算值决定。
默认值为
auto。 block可选-
定义元素在可滚动祖先容器中的垂直对齐方式。其值可以是以下之一:
start:将元素的上边缘与可滚动容器的顶部对齐,使元素在垂直方向上出现在可见区域的起始位置。center:将元素在垂直方向上居中对齐到可滚动容器的中心,使其定位在可见区域的中间。end:将元素的下边缘与可滚动容器的底部对齐,使元素在垂直方向上出现在可见区域的末尾。nearest:将元素滚动到垂直方向上最近的边缘。如果元素更靠近可滚动容器的顶部边缘,它将对齐到顶部;如果更靠近底部边缘,它将对齐到底部。这会最小化滚动距离。
默认值为
start。 container可选-
定义可滚动祖先容器。其值可以是以下之一:
all:所有可滚动容器都会受到影响(包括视口)。nearest:只有最近的可滚动容器会受到滚动的影响。
默认值为
all。 inline可选-
定义元素在可滚动祖先容器中的水平对齐方式。其值可以是以下之一:
start:将元素的左边缘与可滚动容器的左侧对齐,使元素在水平方向上出现在可见区域的起始位置。center:将元素在水平方向上居中对齐到可滚动容器的中心,使其定位在可见区域的中间。end:将元素的右边缘与可滚动容器的右侧对齐,使元素在水平方向上出现在可见区域的末尾。nearest:将元素滚动到水平方向上最近的边缘。如果元素更靠近可滚动容器的左边缘,它将对齐到左侧;如果更靠近右边缘,它将对齐到右侧。这会最小化滚动距离。
默认值为
nearest。
返回值
无(undefined)。
示例
使用 scrollIntoView()
js
const element = document.getElementById("box");
element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({ block: "end" });
element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
控制顶部/底部对齐
默认情况下,元素对齐到可滚动祖先的顶部(或底部)边缘。要定义自定义间距,请使用 scroll-margin-top 或 scroll-margin-bottom。当页面上有固定标题时,这通常很有用。
HTML
html
<body>
<header class="navbar">Navbar</header>
<main class="content">
<button id="go-to-bottom">Go to bottom</button>
<button id="go-to-top">Go to top</button>
</main>
</body>
CSS
css
.navbar {
height: 50px;
position: sticky;
top: 0;
border-bottom: 1.5px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.content {
height: 2000px;
position: relative;
}
#go-to-bottom {
position: absolute;
top: 10px;
/* Without this, the button will be aligned to the top of the page
instead of bottom of navbar when scrolled */
scroll-margin-top: 60px;
}
#go-to-top {
position: absolute;
bottom: 10px;
scroll-margin-bottom: 0;
}
JavaScript
js
const goToTop = document.getElementById("go-to-top");
const goToBottom = document.getElementById("go-to-bottom");
goToBottom.addEventListener("click", () => {
goToTop.scrollIntoView({ behavior: "instant", block: "end" });
});
goToTop.addEventListener("click", () => {
goToBottom.scrollIntoView({ behavior: "instant", block: "start" });
});
结果
规范
| 规范 |
|---|
| CSSOM 视图模块 # dom-element-scrollintoview |
浏览器兼容性
加载中…