我创建了一个
changeColour
功能,其中导航栏在滚动超过某个点后会改变颜色,效果完美。问题是我只希望它在我的主页上生效,而其他所有页面(关于我们、商店、联系我们)继续使用我的 .navbarbg .nav-list-green a .nav-list-green a:hover
选择器
这是迄今为止我的代码:
导航栏.jsx
'use client'
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import Logo from './Logo.jsx'
import '../App.css'
const Navbar = () => {
const state = useState()
const navigation = [
{_id:101, title: 'ABOUT US', href: '/AboutUs'},
{_id:102, title: 'SHOP', href: '/Shop'},
{_id:103, title: 'MENU', href: '/Menu'},
{_id:104, title: 'CONTACT US', href: '/ContactUs'},
];
const [colour, setColour] = useState(false)
useEffect(() => {
const changeColour = () => {
setColour(window.scrollY >= 650)
};
window.addEventListener('scroll', changeColour);
return () => {
window.removeEventListener('scroll', changeColour)
}
}, [])
return (
<div className={colour ? 'navbar navbarbg' : 'navbar'}>
<div className="container">
<Logo />
<ul className={colour ? 'nav-list-beige nav-list-green' : 'nav-list-beige'}
>
{
navigation.map((item) => (
<Link to={item?.href} key={item._id}>
<li className={colour ? 'nav-link nav-link-colour' : 'nav-link'}>
{item?.title}
<span className={`${item?.href === state && 'style=color: blue;'}`}></span>
</li>
</Link>
))
}
</ul>
<div>
</div>
</div>
</div>
)
}
export default Navbar
我的应用程序.css
/* navbar.jsx CSS */
.navbarbg {
background-color: hsl(0, 0%, 100%);
backdrop-filter: blur(30px);
box-shadow: 1px 1px 5px 1px hsl(0, 0%, 63%);
transition-duration: 500ms;
}
.navbar {
/* (green) background-color: hsl(96, 24%, 44%, 90%); */
/* background-color: hsl(49, 87%, 88%); */
/* border-bottom: 1px solid black; */
position: fixed; top: 0px;
height: 80px;
width: 100%;
z-index:99;
transition-duration: 500ms
}
.nav-list-beige {
display: flex;
gap: 50px;
list-style-type: none;
justify-content: center;
font-size: larger;
display: flex;
position: relative; top: -30px; left: 350px;
}
.nav-list-beige a {
color: hsl(48, 54%, 89%);
text-decoration: none;
transition-duration: 500ms;
}
.nav-list-beige a:hover {
color: hsl(48, 100%, 85%);
transition-duration: 300ms;
text-shadow: 0px 0px 2px;
}
.nav-list-green a {
color: hsl(0, 0%, 0%);
}
.nav-list-green a:hover {
color: hsl(96, 24%, 44%);
}
如有任何建议,我们将不胜感激?谢谢你
在
const changeColour = () => {
setColour(window.scrollY >= 650)
};
部分,你可以有条件,比如
const changeColour = () => {
if (isItHomePage()) setColour(window.scrollY >= 650)
};
然后你需要像
一样实施
isItHomePage
function isItHomePage() {
return window.location.href.indexOf("<your home url>") === 0;
}