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