【问题标题】:window.onscroll css transformY transition flickeringwindow.onscroll css 变换过渡闪烁
【发布时间】:2021-02-14 12:26:30
【问题描述】:

在我的反应项目中,我希望导航在向下滚动时隐藏并在向上滚动时显示。我正在使用窗口事件侦听器进行滚动,它会触发我的 toggleNavigation 函数和 CSS transform: translateYtransition。无论我使用鼠标滚轮、键盘箭头还是拖动滚动条,导航都会在向上或向下滚动时闪烁。 (运行toogleNavigation时还有一些其他条件,但它们不相关。)

导航组件

import React, { useEffect, useState } from "react";

export default Navigation = () => {
  const [prevScrollpos, setPrevScrollpos] = useState(window.pageYOffset);
  const [translateY, setTranslateY] = useState("0");

  const toggleNavigation = (prevScrollpos) => {
    const currentScrollpos = window.pageYOffset;
    if (currentScrollpos > prevScrollpos + 50) {
      //navigationHtml.style.top = '-116px'
      setTranslateY("-116px");
      setPrevScrollpos(currentScrollpos);
    } else if (currentScrollpos + 50 < prevScrollpos) {
      //navigationHtml.style.top = '0'
      setTranslateY("0");
      setPrevScrollpos(currentScrollpos);
    }
  };

  useEffect(() => {
    window.addEventListener(
      "scroll",
      toggleNavigation.bind(this, prevScrollpos)
    );
    return () => {
      window.removeEventListener("scroll", toggleNavigation);
    };
  }, [prevScrollpos]);
  return (
    <nav style={{ transform: `translateY(${translateY})` }}>
      <ul>
        <li>random text 1</li>
        <li>random text 2</li>
      </ul>
    </nav>
  );
};

CSS

nav {
  background-color: orangered;
  position: fixed;
  height: 120px;
  width: 100%;
  transition: transform 0.5s;
}
ul {
  list-style-type: none;
  display: flex;
  justify-content: center;
}
li {
  margin: 20px;
}

工作代码和框: https://codesandbox.io/s/jolly-haze-flfjj?file=/src/Navigation.js

到目前为止,我已经尝试过但没有成功:

在反应中:将隐藏/显示导航的限制从 50 更改为 100 或 1

在 CSS 中:

  • translateY 更改为translate3D
  • 在其他元素上使用translate3D(0,0,0)
  • 在导航和其他元素上设置backface-visibility: hidden

在我使用更改 top 而不是 translateY 之前,但动画并不流畅和活泼,尽管它没有闪烁。 我在 Chrome、Edge、Firefox 和 Opera 中对其进行了测试,所有这些都存在问题。

任何帮助将不胜感激。

【问题讨论】:

  • 它在我的笔记本电脑上运行良好:D
  • 它在我的桌面/Win10/Chrome 上运行良好。
  • 刷新页面后我发现它可以正常工作一会儿。然而,我滚动的越多,它变得越糟糕。

标签: javascript reactjs css-transitions css-transforms


【解决方案1】:

很高兴听到它运行良好。 但是你可以走得更远,因为滚动事件的计算从来都不是一个好主意,因为它被触发了很多次。如果您的网页上有其他滚动事件,它可能会变得缓慢/滞后。

您还可以使用自定义 Hook 为滚动事件添加限制

这是一个节流滚动事件 Hook 的示例(与 SRR 兼容):

    import { useEffect, useState } from "react"
    // You can use Lodash throttle function or aby other one, your own, whatever...
    import { throttle } from "lodash"
    
    function useDocumentScrollThrottled(callback) {
      const [, setScrollPosition] = useState(0)
      let previousScrollTop = 0
    
      function handleDocumentScroll() {
        const { scrollTop: currentScrollTop } =
          typeof window === "undefined" || !window.document
            ? 0
            : document.documentElement || document.body
    
        setScrollPosition(previousPosition => {
          previousScrollTop = previousPosition
          return currentScrollTop
        })
    
        callback({ previousScrollTop, currentScrollTop })
      }
    
      // => 250: 4fps / triggered times per seconds (250 is in milliseconds) || 16: 60fps (because 1000/60 = ~16) 
      const handleDocumentScrollThrottled = throttle(handleDocumentScroll, 250) 
    
      useEffect(() => {
        window.addEventListener("scroll", handleDocumentScrollThrottled)
    
        return () =>
          window.removeEventListener("scroll", handleDocumentScrollThrottled)
      }, [handleDocumentScrollThrottled])
    }
    
    export default useDocumentScrollThrottled

然后在您的组件中(以您的 Nav 组件为例)您可以这样使用它:

export default function Nav() {
      const MINIMUM_SCROLL = 30;
      const TIMEOUT_DELAY = 50;
      const [shouldHideNav, setShouldHideNav] = useState(false)  ;
    
      useDocumentScrollThrottled(({ previousScrollTop, currentScrollTop }) => {
        // Do whatever you want like by example
        const isScrolledDown = previousScrollTop < currentScrollTop;
        const isMinimumScrolled = currentScrollTop > MINIMUM_SCROLL;
        setTimeout(() => {
          setShouldHideNav(isScrolledDown && isMinimumScrolled)
        }, TIMEOUT_DELAY)
      })

      return (<nav className={`nav ${shouldHideNav ? 'nav--hidden' : ''}`}>Nav content</nav>)
}

【讨论】:

    【解决方案2】:

    所以我自己解决了这个问题。问题是我在 React 中的糟糕设计。我不应该使用useState 挂钩来跟踪滚动,因为它会导致按设计重新渲染组件。几卷之后,滞后的行为就很明显了。在性能更高的 PC 上需要更多滚动(更多组件重新渲染)才会滞后。 现在我使用一个简单的let 变量跟踪滚动,并且导航组件仅在显示或隐藏时重新呈现。

    代码沙盒: https://codesandbox.io/s/condescending-minsky-00xi0?file=/src/Navigation.js

    【讨论】:

      猜你喜欢
      • 2018-05-14
      • 1970-01-01
      • 2017-07-03
      • 2015-08-05
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多