滚动开始时调用方法



我有一个使用滚动事件的 react 组件。调用滚动事件时,它基本上按预期运行处理程序。但是,我需要能够在滚动事件开始触发时调用一次方法。我理解在滚动停止时触发的去抖动方法的想法,但我需要找到一种在滚动开始时触发一次的方法。(当然不能使用jQuery)。

componentDidMount() {
window.addEventListener('scroll', this.onScroll);
this.setState({
// sets some state which is compared in a shouldComponentUpdate
});
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll);
}
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}

下面看到的处理程序运行一些代码:

onScroll() {
this.scrollTop = document.documentElement.scrollTop;
this.update();
}

但是我需要一个运行一次的函数:

scrollStart() {
}

我很想说我已经尝试过一些东西,但不幸的是我没有想法。任何协助将不胜感激。

浏览器中没有真正的滚动状态;滚动事件发生,然后结束。

例如,您可以在每次用户滚动时创建一个新的超时,如果用户在运行超时函数之前没有滚动,则将您自己的滚动状态设置为 false。

class App extends React.Component {
timeout = null;
state = { isScrolling: false };
componentDidMount() {
window.addEventListener("scroll", this.onScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.onScroll);
}
onScroll = () => {
clearTimeout(this.timeout);
const { isScrolling } = this.state;
if (!isScrolling) {
this.setState({ isScrolling: true });
}
this.timeout = setTimeout(() => {
this.setState({ isScrolling: false });
}, 200);
};
render() {
return (
<div
style={{
width: 200,
height: 1000,
background: this.state.isScrolling ? "green" : "red"
}}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

您是否希望 scrollStart() 函数只在用户第一次滚动时触发一次?如果是这样,这可以通过 scrollStarted 变量轻松完成。if (scrollStarted == false) { scrollStarted = true; scrollStart(); }.

如果您希望函数在用户开始从顶部滚动时触发,我可以想象类似的场景(如果用户返回顶部,它可以再次触发)。只需将(scrollStarted == false)替换为scrollTop == 0即可。

javascript 中没有scrollstart事件,但是您可以在父元素上注册指针事件并在目标元素上滚动事件。

然后,例如,在pointerdown回调中,重置滚动开始时设置的变量。

如果需要,您甚至可以在触发滚动事件且未设置var scrolling时在目标上调度自定义"scrollstart"事件。

对于document.body,您可以在window上侦听指针(或触摸或鼠标)事件。

为此,您可以定义一个静态变量,当滚动开始时,将true放入变量中并输入一个不断检查 scrool 是否继续的while。使用这个逻辑,你也许可以做一些事情。

最新更新