React项目中实现鼠标悬停切换SVG图片的技术求助
实现鼠标悬停切换SVG的几种可行方案
方案1:纯CSS实现(无需JS)
适合静态场景,代码简洁无额外状态管理。调整组件结构,用带背景图的容器替代<img>,通过:hover伪类切换背景:
// 修改后的组件结构 <button> <a href="#"> <figure> <div className="sebha-icon"></div> <figcaption>{title_sebhag}</figcaption> </figure> </a> </button>
对应的CSS样式:
.sebha-icon { width: 40px; /* 替换为你的SVG实际宽度 */ height: 40px; /* 替换为你的SVG实际高度 */ background-image: url('./assets/Menu/grey/sebha-g.svg'); background-size: contain; background-repeat: no-repeat; } /* 鼠标悬停时切换背景图 */ button:hover .sebha-icon { background-image: url('./assets/Menu/white/sebha-w.svg'); }
如果用CSS Modules,路径写法可调整为:
.sebhaIcon { background-image: url('~assets/Menu/grey/sebha-g.svg'); } button:hover .sebhaIcon { background-image: url('~assets/Menu/white/sebha-w.svg'); }
方案2:React状态+鼠标事件实现
适合需要结合其他逻辑的动态场景,用useState管理当前显示的图片,通过鼠标事件切换状态:
import { useState } from 'react'; import sebhag from "./assets/Menu/grey/sebha-g.svg" import sebhaw from "./assets/Menu/white/sebha-w.svg" export const MenuButton = () => { const [currentImg, setCurrentImg] = useState(sebhag); return ( <button onMouseEnter={() => setCurrentImg(sebhaw)} onMouseLeave={() => setCurrentImg(sebhag)} > <a href="#"> <figure> <img src={currentImg} alt="tasbieh" /> <figcaption>{title_sebhag}</figcaption> </figure> </a> </button> ); };
方案3:CSS滤镜实现(仅适用于颜色差异的SVG)
如果两张SVG仅颜色不同(灰色/白色),无需切换图片,直接用filter属性修改颜色更高效:
.sebha-img { filter: grayscale(100%); /* 初始灰色效果 */ } button:hover .sebha-img { filter: grayscale(0%) brightness(0) invert(1); /* 转为白色 */ }
组件结构保留原有<img>并添加类名:
<img src={sebhag} alt="tasbieh" className="sebha-img" />
注:需根据SVG实际颜色调整filter参数,确保效果符合预期。
内容的提问来源于stack exchange,提问作者Majdi Ed
相关产品推荐
相关产品推荐

