需求背景
在长表单填写中,有时候在表单提交的时候需要定位到出错的表单项,以便给用户更好的体验
方法一
直接调用js的scrollIntoView方法,具体用法参考webApi
// 需要显示的元素
const element = document.getElementById("box");
// 元素的顶部将与可滚动祖先的可见区域的顶部对齐
element.scrollIntoView();
方法二
上述方法存在一些兼容问题,如果对兼容性要求比较高,可以采用 scroll-into-view-if-needed插件
import scrollIntoView from 'smooth-scroll-into-view-if-needed';
scrollIntoView(node, {
behavior: 'smooth',
scrollMode: 'if-needed',
});