【问题标题】:Sticky header animation working when scrolling down but not when scrolling up粘性标题动画在向下滚动时有效,但在向上滚动时无效
【发布时间】:2021-10-03 02:24:23
【问题描述】:

代码沙箱:https://codesandbox.io/s/nostalgic-morning-3f09m?file=/src/App.tsx

所以,我有一个粘性标题,一旦用户滚动了 X 像素(本例中为 420 像素),它就会出现。一旦达到 420 像素,它就会显示一个向下滑动标题的动画。但是,当我向上滚动屏幕时,粘性标题会以一种非常冷酷的方式“消失”。这个想法是它也会“滑动”起来,然后以相反的方式消失。我想要实现的一个例子-> https://www.pretto.fr/ 我想要这个,当标题向下滑动时,当我向上滚动时,它向上滚动消失。

不同之处在于,在这个网站中,粘性标题和“主”标题似乎是两个不同的组件。在我的网站上,它们只是一个,我只是使用道具让它从position: relative; 变为position: sticky;

我的标题:

function Header(props: HeaderProps): React.ReactElement {
  const [sticky, setSticky] = useState(false)

  useEffect(() => {
    document.addEventListener('scroll', trackScroll)

    return () => {
      document.removeEventListener('scroll', trackScroll)
    }
  }, [])

  const trackScroll = () => {
    if (typeof window == 'undefined') {
      return
    } else {
      setSticky(window.scrollY >= 420)
    }
  }

  return (
    <Container id="container" sticky={sticky} className={`${sticky ? 'sticky' : ''}`}>
    ...

还有我的 styled-components 样式...

const smoothScroll = keyframes`
  0% { transform: translateY(-100%); }
  100% { transform: translateY(0px); }
`

const Container = styled.div<{ sticky?: boolean }>`
  display: flex;
  justify-content: space-between;
  margin: auto;
  padding: 0 6rem;
  width: 100%;
  position: ${props => (props.sticky ? 'sticky' : 'relative')};
  top: 0px;
  height: 97px;
  align-items: center;
  z-index: 3;
  background: ${props => (props.sticky ? 'white' : 'inherit')};

  &.sticky {
    animation: ${smoothScroll} 500ms;
  }
`

所以当我向下滚动到 420 像素时,漂亮的“向下滑动”动画就会起作用。但是一旦我向上滚动它就会消失而不是“向上滑动”。关于如何实现这一点的任何想法?

【问题讨论】:

  • 如果您访问您提供的网站,向下滚动并在 chrome 开发人员选项卡中截取完整尺寸的屏幕截图 - 您会注意到该网站上同时有两个导航。第二个粘性导航只是像你一样改变变换,但没有动画部分 - 动画是通过过渡完成的:transform ease 300ms
  • @SimonDubek 是的,我提到过。我的问题是是否有可能在没有 2 个导航的情况下实现这个动画......

标签: javascript css reactjs typescript


【解决方案1】:

我添加了另一个粘性导航,它使用内联样式来更改变换和过渡以对其进行动画处理。您也可以通过更改原始导航上的位置和其他一些样式来实现这一点,从而摆脱第二个粘性导航,但我认为这更清楚。

这对你有用吗:https://codesandbox.io/s/zen-raman-qtitt

【讨论】:

  • 感谢您抽出宝贵时间。该演示无法正常工作,它对您有用吗?看起来“stickyStyle”有问题
  • 它现在应该可以工作了,顺便说一句,很抱歉没有正确阅读您的问题,我太着急回答了,我只是跳过了您承认两个导航系统的部分 - 这完全想回答一个我没有正确阅读的问题。
猜你喜欢
  • 1970-01-01
  • 2019-06-15
  • 2015-07-17
  • 1970-01-01
  • 2014-06-28
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
相关资源
最近更新 更多