scrollIntoView() 不会滚动到任何地方

Nic*_*ick 10 javascript js-scrollintoview

我无法去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>
            ...
        )
    }
Run Code Online (Sandbox Code Playgroud)

Nic*_*ick 31

设置时间延迟后,它起作用了:

scrollToMyRef = (id) => {
      var ref = document.getElementById(id);
      setTimeout(function () {
           ref.scrollIntoView({
               behavior: "smooth",
               block: "start",
           });
      }, 100);
};
Run Code Online (Sandbox Code Playgroud)

  • 与OP同样的问题,但这次延迟并没有为我解决问题。在我删除行为:平滑之前,我的仍然根本不滚动。 (2认同)
  • 这取决于您在什么时候调用“scrollToMyRef”,但如果是在状态更改之后,而没有实际等待状态更改渲染,那么这可能是“setTimeout”解决您的问题的原因。如果是这种情况,您可以使用 setTimeout(..., 0) ,也就是说,根本不需要等待,只需在事件循环的下一次迭代时运行该函数即可。 (2认同)