-
目标效果,以圆通速递官网为例
–滑动一定高度后
-
代码
–代码块
const reductionStyle = {
position:"absolute",
top:"3.75rem",
width:"80%",
borderRadius:"40px",
marginLeft:"10%",
zIndex:"9999"
}
function ChangeNav() {
let handleScroll = function(){
// console.log("111")
let changeNav_box = document.querySelector(".changeNav-box");
let scrollY = window.scrollY;
// console.log(scrollY)
if(scrollY >= 30){
changeNav_box.style.position="fixed";
changeNav_box.style.top="1.875rem";
changeNav_box.style.width="100%";
changeNav_box.style.marginLeft="0px"
changeNav_box.style.borderRadius="0px"
}else{
// changeNav_box.style.position="absolute";
// changeNav_box.style.top="3.75rem"
// changeNav_box.style.width="80%"
// changeNav_box.style.borderRadius="40px"
// changeNav_box.style.marginLeft="10%"
changeNav_box.style={reductionStyle}
}
}
useEffect(()=>{
console.log("222")
window.addEventListener("scroll",handleScroll)
handleScroll()
})
–reductionStyle 写的是样式,可以提前在函数之前声明
**=========更新===========**
useEffect中要移除刚刚监听的事件,否则如果有路由跳转到下个页面会继续监听,而此时页面上已经没有handleScroll方法了
- 代码
useEffect(() => {
// console.log("222")
window.addEventListener("scroll", handleScroll)
handleScroll()
return () => {
window.removeEventListener("scroll", handleScroll)
}
})