You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中滚动切换导航栏时悬停颜色不生效问题求助

导航栏滚动后悬停样式不生效问题解决

问题描述

已实现滚动时切换导航栏背景和文字颜色的功能,但滚动超过650px后,导航链接的悬停样式仍使用.nav-list a:hover,而非预期的.nav-list-colour a:hover。

问题原因

CSS选择器优先级冲突:.nav-list a:hover和.nav-list-colour a:hover的优先级相同,且前者在样式表中位置靠后,导致后者被覆盖。

解决方案

1. 提升CSS选择器优先级

修改style.css中的悬停样式,通过组合类选择器提升.nav-list-colour a:hover的优先级:

/* 替换原有.nav-list-colour a:hover样式 */
.nav-list.nav-list-colour a:hover {
  color: rgb(200, 181, 103);
}

该选择器同时匹配两个类名,优先级高于单个类名的.nav-list a:hover,滚动后悬停样式会正常生效。

2. 修复React组件中的无效代码

组件中const state = useState()是错误用法(useState必须传入初始值),且无实际作用,建议删除;若需标记当前活跃路由,可改用useLocation:

// 删除无效代码
// const state = useState()

// 如需路由标记,先导入useLocation
// import { useLocation } from 'react-router-dom'
// const location = useLocation()

// 然后修改span的判断逻辑
<span className={`${item?.href === location.pathname && 'active-link'}`}></span>
// 同时在CSS中添加.active-link样式

修改后的完整CSS代码

.nav-list {
  font-weight: bold;
  display: flex;
  gap: 50px;
  list-style-type: none;
  justify-content: center;
  font-size: larger;
  position: relative; top: -30px; left: 300px;
}

.nav-list a {
  color: hsl(48, 54%, 89%);
  text-decoration: none;
  text-underline-offset: 0.2em;
  transition-duration: 500ms;
}

.nav-list-colour a {
  color: hsl(96, 24%, 44%);
}

.nav-list.nav-list-colour a:hover {
  color: rgb(200, 181, 103);
}

.nav-list a:hover {
  color: hsl(96, 24%, 44%);
  text-underline-offset: 0.4em;
  transition-duration: 300ms;
  text-shadow: 0px 0px 3px;
}

内容的提问来源于stack exchange,提问作者ryanl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:55:35