在滚动方向更改时存储滚动位置

Store Scroll Position on Scroll Direction Change

我正在开发一个 React 模块,该模块根据滚动位置处理显示和隐藏状态元素。我拥有的是功能性的,但我需要能够在方向改变时捕获 scroll position

以下是相关的代码片段,所有绑定和事件侦听器都起作用:

this.state = {
  lastScrollPos: 0,
  down: true
};

_scrollFunction() {
  const thisPos = window.pageYOffset;
  const down = thisPos > this.state.lastScrollPos;

  if (down) {
    this.setState({
      down: true,
      lastScrollPos: thisPos
    });
  } else if (!down) {
    this.setState({
      down: false,
      lastScrollPos: thisPos
    });
  }

}

在上面的 _scrollFunction() 中,设置 lastScrollPos: thisPos 为我提供了页面再次滚动之前的滚动位置。

我的问题是如何捕获滚动方向改变时的滚动位置。如果我向下滚动然后向上滚动,我需要知道它发生的位置,反之亦然。

对此有任何建议,我们将不胜感激!谢谢!

您应该检查 _scrollFunction 当前 down 值是否不同于状态的 down 值。如果是,将thisPos值写入changedPos状态变量。

工作示例:

constructor() {
  super();

  this.state = {
    lastScrollPos: 0,
    changedPos: undefined,
    down: true
  };
}

_scrollFunction() {
  const thisPos = window.pageYOffset;
  const down = thisPos > this.state.lastScrollPos;
  // If current `down` value is differs from `down` from state,
  // assign `thisPos` to variable, else assigning current `changedPos` state value.
  const changedPos = down !== this.state.down ? thisPos : this.state.changedPos;

  this.setState({
    lastScrollPos: thisPos,
    changedPos,
    down
  });
}

此外,我已经在 CodePen 上制作了工作演示,您可以查看它以获取更多信息。