赞
踩
代码主要实现了导航栏跟随页面显示隐藏,页面向下滚动时导航栏消失,向上滚动导航栏显示,这个可以动态的去调整
.show {
position: fixed;
top: 0px;
transition: 0.3s linear;
background-color: #ffffff;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
box-shadow: 0 2px 5px -1px rgba(0, 0, 0, 0.08);
}
.hide {
position: fixed;
top: -65px;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
box-shadow: 0 2px 5px -1px rgba(0, 0, 0, 0.08);
transition: 0.3s linear;
}
这里有一点需要注意:在我们去监听滚动的时候需要重新定义一个新的变量用于根据新老元素滚动的偏移量来判断导航栏的显示和隐藏
声明一个状态用于控制显示和隐藏,在useEffect
中进行监听和销毁操作
const [isShow, setIsShow] = useState(false)
useEffect(() => {
// 监听
window.addEventListener('scroll', handleScroll)
// 销毁
return () => window.removeEventListener('scroll', handleScroll)
}, [])
在回调函数中拿到scrollTop
偏移量的值
let lastScrollTop = 0; const handleScroll = () => { let clientHeight = document.documentElement.clientHeight //可视区域高度 let scrollTop = document.documentElement.scrollTop; //滚动条滚动高度 let scrollHeight = document.documentElement.scrollHeight; //滚动内容高度 // console.log("scrollTop", scrollTop, 'lastScrollY', lastScrollTop, 'clientHeight', clientHeight, 'scrollHeight', scrollHeight); if (scrollTop > lastScrollTop) { setIsShow(true) } else { setIsShow(false) } lastScrollTop = document.documentElement.scrollTop // 判断是否滚动到底部 if (scrollTop + clientHeight === scrollHeight) { console.log("滚动到底部"); } }
判断样式状态,进行显示和隐藏
<div>
<Header className={`show ${isShow && 'hide'}`}>
<Menu
items={items}
mode="horizontal"
selectedKeys={selectKeys}
onClick={handleSwitch}
/>
</Header>
</div >
页面导航栏正常根据滚动偏移量进行显示和隐藏~
参考链接:
How to reveal a React component on scroll
个人博客已上线,欢迎来访~
传送门:夜雨炊烟
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。