我在解决方案中使用了offsetTop,如下所示。
public getOffsetTop = element => {
let offsetTop = 0;
while (element) {
offsetTop += element.offsetTop;
element = element.offsetParent;
}
return offsetTop;
};
const field = document.getElementById("error");
const totalOffsetTop = this.getOffsetTop(field);
window.scrollTo({
top: totalOffsetTop,
behavior: "smooth"
});
这很顺利。每当出现错误时,我都可以自动滚动回到错误字段。但是,这是真正的问题。 offsetTop是实验性的,不应在生产中使用。 https://caniuse.com/#feat=mdn-api_htmlelement_offsettop
我尝试使用getBoundingClientRect()。top,但是它不会滚动回到错误字段。任何人都可以提出更好的选择吗?
您可以:
document.getElementById("error").scrollIntoView({ behavior: 'smooth' });