【问题标题】:Stop React spring animation if user scrolls while animating如果用户在动画时滚动,则停止 React 弹簧动画
【发布时间】:2020-02-26 04:32:45
【问题描述】:

我正在使用 react spring 在组件安装后 500 ms 为窗口滚动设置动画。如果滚动动画和用户的滚动同时发生,就会出现问题。 我让它在开始动画之前检查页面滚动是否为 0,但这只有在用户在 500 毫秒触发之前滚动时才能解决。

代码如下:

const [, setY] = useSpring(() => ({ y: window.innerHeight * 0.05 }))

useEffect(() => {
    setTimeout(() => {
        // Cross browser way of knowing how much the user has scrolled the page.
        const scrollTop = (window.pageYOffset !== undefined)
            ? window.pageYOffset
            : (document.documentElement || document.body.parentNode || document.body).scrollTop
        // Checks if the user hasn't scrolled himself.
        if (scrollTop === 0) {
            // Animates.
            setY({
                y: window.innerHeight * 0.05,
                reset: true,
                from: { y: window.scrollY },
                onFrame: props => window.scroll(0, props.y)
            })
        }
    }, 500)
}, [])

我也尝试将 stop 函数解构为 onFrame 并在其中使用它,但它似乎不起作用:

const [, setY, stop] = useSpring(() => ({ y: window.innerHeight * 0.05 }))

还有window.scroll() 触发scroll 事件,所以我无法区分脚本滚动和用户滚动。

关于如何解决这个问题的任何想法?

提前致谢!

【问题讨论】:

    标签: reactjs react-spring


    【解决方案1】:

    我用这个:let user scrolling stop jquery animation of scrolltop?

    我制作了自己的基于反应的事件处理程序

      const cancelEvents = [
        "scroll",
        "mousedown",
        "DOMMouseScroll",
        "mousewheel",
        "keyup",
        "touchstart",
        "touchmove",
      ];
    
      const cancelAnimationHandler = useCallback((e) => {
        if (
          e.which > 0 ||
          cancelEvents.reduce(
            (accumulator, currentValue) =>
              e.type === accumulator || e.type === currentValue
          )
        ) {
          api.stop();
        }
      }, []);
      useEffect(() => {
        cancelEvents.map((event) =>
          window.addEventListener(event, cancelAnimationHandler)
        );
        () =>
          cancelEvents.map((event) =>
            window.removeEventListener(event, cancelAnimationHandler)
          );
      }, [cancelAnimationHandler]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 2016-03-27
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      相关资源
      最近更新 更多