【发布时间】:2022-10-18 17:58:18
【问题描述】:
我无法让Element.scrollIntoView() 工作。我有下面的代码。它应该滚动到两个位置,具体取决于某些变量。但是,它不会滚动到其中任何一个。我究竟做错了什么?
class Page extends Component {
scrollToMyRef = (id) => {
var ref = document.getElementById(id);
console.log("Ref1: " + ref); // returns [object HTMLElement]
console.log("Ref2: " + document.ref); // returns undefined
console.log("Id: " + id); // returns myRef
ref.scrollIntoView({
behavior: "smooth",
block: "start",
});
};
componentDidMount() {
if (this.props.location.state) {
if (this.props.location.state.origine) {
this.scrollToMyRef("myRef");
} else {
this.scrollToMyRef("myTopRef");
});
}
}
}
render() {
return (
<div
id="myTopRef"
key="pricing"
className="pricing"
>
...
</div>
<section id=myRef className="section">
...
</section>
...
)
}
【问题讨论】:
-
您可能需要显示您的 CSS 和标记:元素
#myRef在溢出的父母?scrollIntoView仅在元素本身位于视口之外 + 其父元素可滚动时才有效。 -
在
block属性中,尝试指定nearest而不是start,但不能保证。不久前我在表格中使用了它,它的工作原理如 Terry 所述:仅当元素位于视口之外时。 -
不幸的是,这似乎没有什么不同。它仍然没有滚动。
-
有趣的是,如果我删除
behavior: "smooth",或将其设置为auto,我的原始代码就可以工作。知道这是为什么吗?我想使用平滑的行为...... -
我已经让它工作了。我需要设置一个时间延迟:`scrollToMyRef = (id) => { var ref = document.getElementById(id); setTimeout(function () { ref.scrollIntoView({ behavior: "smooth", block: "start", }); }, 100); };`
标签: javascript js-scrollintoview