scrollIntoView() 不会滚动到任何地方
scrollIntoView() doesn't scroll anywhere
我无法让 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>
...
)
}
设置时间延迟后它起作用了:
scrollToMyRef = (id) => {
var ref = document.getElementById(id);
setTimeout(function () {
ref.scrollIntoView({
behavior: "smooth",
block: "start",
});
}, 100);
};
我无法让 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>
...
)
}
设置时间延迟后它起作用了:
scrollToMyRef = (id) => {
var ref = document.getElementById(id);
setTimeout(function () {
ref.scrollIntoView({
behavior: "smooth",
block: "start",
});
}, 100);
};