【问题标题】:Sticky header animating when appearing but not when disappearing粘性标题在出现时动画,但在消失时不动画
【发布时间】:2021-10-02 18:51:41
【问题描述】:

编辑:这是我的沙盒https://codesandbox.io/s/nostalgic-morning-3f09m?file=/src/App.tsx

所以,我在 React/Gatsby 上制作了一个粘性标题,一旦屏幕滚动 Y >= 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 像素时,漂亮的“向下滑动”动画就会起作用。但是一旦我向上滚动它就会消失而不是“向上滑动”。关于如何实现这一点的任何想法?

【问题讨论】:

标签: javascript reactjs typescript sass styled-components


【解决方案1】:

动画只会在 'sticky' 类被添加到元素时触发,而不是被移除。一种可能的解决方案是跟踪向上滚动事件并添加另一个具有“向上滑动”动画的类,其中包含反转样式 - general concept

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-06
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 2016-11-15
    相关资源
    最近更新 更多