JavaScript scrollIntoView

描述

Element 方法 scrollIntoView:滚动父级容器,使得元素出现在视口。

参数

属性类型可选值
alignToTopbooleantrue,false
scrollIntoViewOptionsobject{ behavior: 'auto' / 'smooth', block: 'start' / 'center' / 'end' / 'nearest', inline: 'start' / 'center' / 'end' / 'nearest'}

alignToTop

  • 当传入参数true时,相当于{behavior: 'auto', block: 'start', inline: 'nearest'}
  • 当传入参数false时,相当于{behavior: 'auto', block: 'end', inline: 'nearest'}

当未传入参数时,默认值为:{behavior: 'auto', block: 'start', inline: 'nearest'}

scrollIntoViewOptions

属性描述可选值默认值
behavior定义过渡动画auto / smoothauto
block定义垂直方向的对齐start / center / end / neareststart
inline定义水平方向的对齐start / center / end / nearestnearest

nearest :

  • 如果元素完全在视口内,则水平方向不发生滚动。
  • 如果元素未能完全在视口内,则根据最短滚动距离原则,水平方向滚动父级容器,使元素完全在视口内。

示例

1
2
3
4
5
6
var element = document.getElementById("box");
element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({block: "smooth"});
element.scrollIntoView({behavior: "instant", block: "end", inline: "nearest"});

表单校验不通过,页面滚动到出错的位置!

1
2
3
4
5
6
7
8
 if (!valid) {
this.$nextTick(() => {
// 表单校验不通过,页面滚动到出错的位置
const errorFormItem = this.$el.querySelector('.el-form-item__error').parentNode;
errorFormItem.scrollIntoView({ behavior: 'smooth' });
});
return;
}