I have written a simple navbar that has a scroll animation. Example:
<div className={"nav active"}>
Here CSS on active
is not working. Even if I write .active
or nav.active
in my CSS file, I have no result. In my code I have used a on scroll
event listener so when I scroll down, the navbar appears black and when I go on the navbar, it disappears. But the problem is that CSS is working in nav
, but not working in active
and as a result black color in active
is not appearing.
const [show , handleshow]= useState(false);
const transitionNavBar = () => {
if (window.scroll > 100){
handleshow(true);
}else{
handleshow(false);
}
};
useEffect(() => {
window.addEventListener("scroll",transitionNavBar);
return () => window.removeEventListener("scroll", transitionNavBar);
}, []);
return (
<div className={`nav ${show && "active"}`}>
<div className="nav_contents">
<img className='nav_logo'
src="http://assets.stickpng.com/images/580b57fcd9996e24bc43c529.png"
alt=""
/>
<img className='nav_avatar' src="https://i.pinimg.com/originals/0d/dc/ca/0ddccae723d85a703b798a5e682c23c1.png"
alt=""
/>
</div>
</div>
)
}
.nav{
position: fixed;
top: 0;
padding: 20px;
width: 100%;
height: 30px;
z-index: 1;
}
.nav.active{
background-color: #111;
}
.nav_contents{
display: flex;
justify-content: space-between;
}
.nav_logo{
position: fixed;
top: 10px;
left: 0%;
width: 80px;
object-fit: contain;
padding-left: 20px;
cursor: pointer;
}
.nav_avatar{
position: fixed;
cursor: pointer;
right: 20px;
width: 30px;
height: 30px;
}
Instead of this
<div className={`nav ${show && "active"}`}>
Try this:
<div className={`nav ${show ? "active":""}`}>
I think you need to write your CSS in a seperate file, if you are not using styled components for example. Write your CSS classes inside a seperate file and then import the css file inside your JSX/JS.
For example:
import "./navbar.css"
Edit: Sorry, just reread and noticed your nav is working. As the other posts suggest, you would probably need to use a conditional operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
我不知道是什么问题,但我再次卸载了 ns install vs code 我的问题解决了我真的不知道它是如何工作的,但它确实有效。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.