我在我的解决方案中使用了 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' });
关于javascript - html offsetTop 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59586599/