代码沙箱:https://codesandbox.io/s/nostalgic-morning-3f09m?file=/src/App.tsx
所以,我有一个粘性标题,一旦用户滚动了 X 个像素(在本例中为 420px),它就会出现。一旦达到 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' : ''}`}>
...
还有我的样式组件样式...
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 像素,漂亮的“下滑”动画就会起作用。但是一旦我向上滚动它就会消失而不是“向上滑动”。关于如何实现这一目标的任何想法?
答案 0 :(得分:1)
我添加了另一个粘性导航,它使用内联样式来更改变换和过渡以使其动画化。您也可以通过更改原始导航上的位置和其他一些样式来实现这一点,从而摆脱第二个粘性导航,但我认为这要清晰得多。