【问题标题】:Store Scroll Position on Scroll Direction Change在滚动方向更改时存储滚动位置
【发布时间】:2016-08-04 17:31:28
【问题描述】:

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

这里是相关代码sn-ps,所有绑定和事件监听器都可以正常工作:

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 会在页面再次滚动之前为我提供滚动位置。

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

对此的任何建议表示赞赏!谢谢!

【问题讨论】:

    标签: reactjs jsx


    【解决方案1】:

    您应该检查_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 上做了工作演示,您可以查看它以获取更多信息。

    【讨论】:

    • 漂亮,这正是我需要的解释。感谢您抽出宝贵时间帮助我!
    猜你喜欢
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    相关资源
    最近更新 更多