代码之家  ›  专栏  ›  技术社区  ›  Aaron Balthaser

开始滚动时调用方法

  •  1
  • Aaron Balthaser  · 技术社区  · 7 年前

    我有一个使用滚动事件的react组件。当调用scroll事件时,它基本上按预期运行处理程序。不过,当滚动事件开始触发时,我需要能够调用一次方法。我理解当滚动停止时会触发的去噪方法的想法,但是我需要找到当滚动开始时触发一次的方法。(确保不能使用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() {
    
    }
    

    我很想说我试过什么,但不幸的是我没有主意。如有任何帮助,将不胜感激。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Tholle    7 年前

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

    例如,每次用户滚动时,您可以创建一个新的超时,如果用户在运行超时功能之前没有滚动,则将您自己的滚动状态设置为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>
        2
  •  0
  •   Sam Holloway    7 年前

    是否希望scrollStart()函数只在用户第一次滚动时触发一次?如果是这样的话,使用scrollStarted变量可以很容易地实现这一点。 if (scrollStarted == false) { scrollStarted = true; scrollStart(); } .

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

        3
  •  0
  •   Isdeniel    7 年前

    为此,您可以定义一个静态变量,当滚动开始时,将 true 在变量中输入 while 一直在检查阴囊是否还在继续。用这个逻辑,你也许能做点什么。