scrollIntoView()方法将指定的元素滚动到浏览器窗口的可见区域。
用法:
document.getElementById("id").scrollIntoView(alignTo);
参数:
alignTo:它是一个布尔类型参数,包含true或false值。默认值设置为true。true:将元素滚动到其窗口顶部。
false:将元素滚动到其窗口的底部。
请注意,基本术语不是“顶部”或“底部”,我将在下一部分中进行介绍。
因此,就像在按钮上分配了特定窗口坐标或元素的鼠标悬停在各个窗口中的元素上一样。
例:
#element {
height:200px;
width:350px;
overflow:auto;
background:green;
}
#content1 {
margin:500px;
height:100px;
width:1000px;
background-color:white;
}
#content2 {
margin:500px;
height:50px;
width:1000px;
background-color:grey;
}
#content3 {
margin:500px;
height:150px;
width:1000px;
background-color:coral;
}
function myFunction1() {
var e = document.getElementById("content1");
e.scrollIntoView(false); // Makes the element
}
function myFunction2() {
var e = document.getElementById("content2");
e.scrollIntoView(true);
}
function myFunction3() {
var e = document.getElementById("content3");
e.scrollIntoView(); // Default is true
}
GeeksforGeeks
Scroll to element-1
Scroll to element-2
Scroll to element-3
Click on the scroll button to see
that elements in a click.
Element-1
Element-2
Element-3
输出:
因此,在上面,项目之间的转换不是很顺畅,只是元素之间的跳跃。
为了使它看起来很酷,为此使用了对象参数。
用法:
document.getElementById("id").scrollIntoView({
behavior:smooth | auto;
block:start | center | end | nearest;
inline:start | center | end | nearest;
});
行为对象确定滚动的平滑度有两种模式:“平滑”和“自动”。块对象确定元素视图应从块的哪一部分开始。内联对象确定视图应从元素的哪个对齐开始。
例:
#element {
height:200px;
width:350px;
overflow:auto;
background:green;
}
#content1 {
margin:500px;
height:100px;
width:1000px;
background-color:white;
}
#content2 {
margin:500px;
height:50px;
width:1000px;
background-color:grey;
}
function myFunction1() {
var e = document.getElementById("content1");
e.scrollIntoView({
block:'start',
behavior:'smooth',
inline:'start'
});
}
function myFunction2() {
var e = document.getElementById("content2");
// Ends the block to the window
// Bottom and aligns the view to the center
e.scrollIntoView({
block:'end',
behavior:'smooth',
inline:'center'
});
}
GeeksforGeeks
Scroll to element-1
Scroll to element-2
Click on the scroll button to
see that elements in a click.
Element-1 aligned to start
Element-2 aligned to center
输出: