0

代码沙箱: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 像素,漂亮的“向下滑动”动画就会起作用。但是一旦我向上滚动它就会消失而不是“向上滑动”。关于如何实现这一目标的任何想法?

4

1 回答 1

1

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

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

于 2021-07-27T10:15:06.323 回答