【问题标题】:Javascript, scroll event listener doesn't fire until scroll is done on mobileJavascript,滚动事件侦听器在移动设备上完成滚动之前不会触发
【发布时间】:2017-06-18 12:40:21
【问题描述】:

我正在使用事件侦听器进行滚动,它将根据用户在页面上的位置将页面上的按钮从 position:fixed 更改为 position:relative。我有一个非常简单的设置,我正在使用反应,当反应组件安装时,我为滚动事件添加了一个带有节流器的侦听器。这在桌面上效果很好,但是在移动设备上,我注意到更改元素位置的事件在滚动完成之前不会触发。

这是我的设置 -

在组件挂载上,添加监听器:

 componentDidMount() {
    window.addEventListener('scroll', this.scrollThrottler);
  }

调用节流函数:

  let scrollTimeout;
  scrollThrottler() {
    // pass through throttle designated at 15 fps
    if ( !scrollTimeout ) {
      scrollTimeout = setTimeout(() => {
        scrollTimeout = null;
        this.handleScroll();
      }, 66);
    }
  }

然后它调用的函数只是检查 DOM 上正确点的某个 div 是否像这样更改其上的类:

 handleScroll() {
    const width = this.state.windowWidth ? this.state.windowWidth : window.innerWidth;
    const stickyBoundary = this.refs.approved.getBoundingClientRect().top + this.refs.approved.offsetHeight + this.refs.stickyBar.offsetHeight - window.innerHeight;

    if ( (width <= 991) && (stickyBoundary > 0)) {
      this.refs.rootNode.className = 'row primary-product-block sticky-add-btn';
    } else {
      this.refs.rootNode.className = 'row primary-product-block';
    }

}

所以这在桌面上效果很好,但是在移动设备上它看起来直到滚动事件完成后才捕捉到固定或相对位置。有没有办法解决这个问题?谢谢!

【问题讨论】:

    标签: javascript html reactjs mobile scroll


    【解决方案1】:

    将 touchmove 事件添加到您的代码中

    componentDidMount() {
       window.addEventListener('scroll', this.scrollThrottler);
       window.addEventListener('touchmove', this.scrollThrottler);
    }
    

    【讨论】:

    • 这不会同时触发滚动和触摸移动吗?
    • 在componentWillUnmount上移除EventListener也是个好主意吗?
    • @RJM 是的,我正在这样做,我只是没有在这个例子中展示。
    猜你喜欢
    • 2022-01-28
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多