【问题标题】:scrollIntoView() doesn't scroll anywherescrollIntoView() 不会滚动到任何地方
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 这解决了我的问题,让我很开心!!!不过,不知道它为什么会起作用。
  • 和 OP 一样的问题,但是这个时间延迟并没有为我解决。在我删除行为之前,我的仍然根本不滚动:平滑。
【解决方案2】:

非常感谢你。搜索过去 2 小时的解决方案,并发现您的回复可以解决我的问题。

【讨论】:

    猜你喜欢
    • 2013-06-21
    • 2019-03-17
    • 2019-03-02
    • 2019-05-13
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2014-08-31
    相关资源
    最近更新 更多