React中如何为<area>标签添加鼠标悬停边框效果
React实现image map区域悬停显示边框方案
核心逻辑和原生实现一致,利用area元素的focus状态自带轮廓实现边框效果,无需额外依赖。
实现方式1:直接绑定事件(静态area场景推荐)
直接在每个<area>标签上声明React鼠标事件,符合React声明式写法,无需操作DOM:
import React from 'react'; const ImageMap = () => { return ( <div> <img src="workplace.jpg" alt="Workplace" useMap="#workmap" width="400" height="379" /> <map name="workmap"> <area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm" onMouseOver={(e) => e.target.focus()} onMouseOut={(e) => e.target.blur()} /> <area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm" onMouseOver={(e) => e.target.focus()} onMouseOut={(e) => e.target.blur()} /> <area shape="circle" coords="337,300,44" alt="Cup of coffee" href="coffee.htm" onMouseOver={(e) => e.target.focus()} onMouseOut={(e) => e.target.blur()} /> </map> </div> ); }; export default ImageMap;
如果需要自定义边框样式,添加对应的CSS即可:
area:focus { /* 自定义边框颜色、粗细、偏移量 */ outline: 2px solid #ff0000; outline-offset: 2px; }
实现方式2:批量绑定事件(动态area场景推荐)
如果area是动态渲染生成、数量不固定,可以通过ref获取map节点统一绑定事件,注意组件卸载时清除事件避免内存泄漏:
import React, { useEffect, useRef } from 'react'; const ImageMap = () => { const mapRef = useRef(null); useEffect(() => { if (!mapRef.current) return; const areas = mapRef.current.getElementsByTagName('area'); const cleanCallbacks = []; Array.from(areas).forEach(area => { const handleMouseOver = (e) => e.target.focus(); const handleMouseOut = (e) => e.target.blur(); area.addEventListener('mouseover', handleMouseOver); area.addEventListener('mouseout', handleMouseOut); cleanCallbacks.push(() => { area.removeEventListener('mouseover', handleMouseOver); area.removeEventListener('mouseout', handleMouseOut); }); }); return () => { cleanCallbacks.forEach(fn => fn()); }; }, []); return ( <div> <img src="workplace.jpg" alt="Workplace" useMap="#workmap" width="400" height="379" /> <map name="workmap" ref={mapRef}> {/* 此处支持静态编写或动态遍历生成area标签 */} <area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm" /> <area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm" /> <area shape="circle" coords="337,300,44" alt="Cup of coffee" href="coffee.htm" /> </map> </div> ); }; export default ImageMap;
内容的提问来源于stack exchange,提问作者Ganesh Gudghe
相关产品推荐
相关产品推荐

