更改React js中滚动的突出显示颜色

问题描述 投票:0回答:1

我的 Navbar.jsx 组件代码有问题。我已经实现了一个功能,导航栏背景和文本在滚动时改变颜色,效果很好,但我想要的是:悬停颜色也生效,但只有一种悬停颜色生效。

到目前为止,只有 'nav-list' a:hover 选择器生效,但滚动超过 650px 后,当我希望它使用 'nav-list-colour' a:hover 选择器时,它仍然使用 'nav-list' a:hover就在那时。

Navbar.jsx 组件

import React, { useState } from 'react'
import Logo from './Logo.jsx'
import '../App.css'

const Navbar = () => {
    const state = useState()

    const navigation = [
      {_id:101, title: 'ABOUT US', href: '/'},
      {_id:102, title: 'SHOP', href: '/Shop'},
      {_id:103, title: 'MENU', href: '/Careers'},
      {_id:104, title: 'CONTACT US', href: '/Contact-Us'},
    ];
    
    const [colour, setColour] = useState(false)

    const changeColour = () => {
      if (window.scrollY >= 650) {
        setColour(true) 
      } else {
        setColour(false)
      }
    }

    window.addEventListener('scroll', changeColour)

  return (
    <div className={colour ? 'navbar navbarbg' : 'navbar'}>
      <div className="container">
        <Logo />
        <ul 
          className={colour ? 'nav-list nav-list-colour' : 'nav-list'}
          >
          {
            navigation.map((item) => (
              <a href={item?.href} key={item._id}>
                <li>
                  {item?.title}
                  <span className={`${item?.href === state && 'style=color: blue;'}`}></span>
                </li>
              </a>
            ))
          }
        </ul>
        <div>
          
        </div>
      </div>
    </div>
  )
}

export default Navbar

这是我的 style.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(96, 24%, 44%); */
  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-colour a:hover {
  color: rgb(200, 181, 103);
}

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

我尝试使用 if 语句设置另一个函数,仅影响颜色,但它停止显示所有更改。任何帮助将不胜感激。谢谢你。

css reactjs react-hooks scroll navbar
1个回答
0
投票

这可能是 CSS 特异性问题。尝试将 UL 组件更改为

<ul className={colour ? 'nav-list colour' : 'nav-list'} >

并将 CSS 更新为此

.nav-list.colour a:hover {
  color: rgb(200, 181, 103);
}
© www.soinside.com 2019 - 2024. All rights reserved.