2016-08-04 90 views
0

我正在处理显示和隐藏基于滚动位置的状态元素的反应模块。我拥有的是功能性,但我需要能够在方向改变时捕获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给我的页面滚动再次向右前滚动位置。

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

对此表示赞赏!谢谢!

回答

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工作演示,你可以检查出来,了解更多信息。

+0

美丽,这正是我需要的解释。感谢您花时间帮助我解决这个问题! –