在 React 应用程序中,我调用了一个方法来将特定节点置于视图中,如下所示。
scrollToQuestionNode(id) {
const element = document.getElementById(id);
element.scrollIntoView(false);
}
滚动发生得很好,但滚动动作有点生涩。我怎样才能使它顺利?我没有看到任何可以为 scrollIntoView 提供的选项。
在 React 应用程序中,我调用了一个方法来将特定节点置于视图中,如下所示。
scrollToQuestionNode(id) {
const element = document.getElementById(id);
element.scrollIntoView(false);
}
滚动发生得很好,但滚动动作有点生涩。我怎样才能使它顺利?我没有看到任何可以为 scrollIntoView 提供的选项。
这可能会有所帮助。
来自 scrollIntoView 的 MDN 文档 您可以传入选项而不是布尔值。
scrollIntoViewOptions Optional
A Boolean or an object with the following options:
{
behavior: "auto" | "instant" | "smooth",
block: "start" | "center" | "end" | "nearest",
inline: "start" | "center" | "end" | "nearest",
}
所以你可以像这样简单地传递参数。
scrollToQuestionNode(id) {
const element = document.getElementById(id);
element.scrollIntoView({ block: 'end', behavior: 'smooth' });
}
参考:https : //developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView
对于多浏览器支持,请使用此处的平滑滚动polyfill
为了便于实现,请使用wrapper
类似polyfill
这样的.js
polyfill
方法,以便在加载后初始化方法:
https://codepen.io/diyifang/embed/MmQyoQ?height=265&theme-id=0&default-tab=js,result&embed-version=2
现在这应该可以跨浏览器工作:
document.querySelector('.foo').scrollIntoView({
behavior: 'smooth'
});
在带有滚动条的 div 上使用此 CSS:
.element-with-the-scrollbar {
overflow-y: scroll;
scroll-behavior: smooth;
}
即使您只是这样做,这也可以平滑滚动:
elementWithTheScrollbar.scrollTop = 0;