如何为图像映射(image map)区域添加:hover效果实现图片切换?
解决图像映射悬停切换主图的问题
问题分析
你之前的尝试失败原因如下:
- CSS方法无效:
<area>是透明行内元素,本身不占据可视化空间,设置background-image无法覆盖下方的主<img>,所以悬停时看不到切换效果。 - jQuery代码语法错误:你写的
('.portfolio').attr(...)缺少jQuery的$符号,正确写法应为$('.portfolio').attr(...),语法错误直接导致事件逻辑不执行。
解决方案
方法一:修正jQuery代码(最直接)
修复语法错误,确保事件绑定的<area>类名与主图选择器准确对应:
<!-- 主图 --> <img class="portfolio" src="原主图地址" usemap="#image-map"> <!-- 图像映射 --> <map name="image-map"> <area class="interactive" shape="poly" coords="你的坐标值" href="#"> <area class="misc" shape="poly" coords="你的坐标值" href="#"> </map>
// 交互区域悬停切换 $(".interactive").on("mouseenter", function(){ $('.portfolio').attr("src", "interactive类对应的图片地址"); }); $(".interactive").on("mouseleave", function(){ $('.portfolio').attr("src", "原主图地址"); }); // 杂项区域悬停切换 $(".misc").on("mouseenter", function(){ $('.portfolio').attr("src", "misc类对应的图片地址"); }); $(".misc").on("mouseleave", function(){ $('.portfolio').attr("src", "原主图地址"); });
方法二:CSS叠加图片实现(无JS)
把所有切换用的图片与主图叠在同一容器,通过<area>的hover/focus状态控制对应图片的显示:
<div class="img-container"> <img class="main-img" src="原主图地址" usemap="#image-map"> <img class="hover-img interactive-img" src="interactive类对应的图片地址"> <img class="hover-img misc-img" src="misc类对应的图片地址"> </div> <map name="image-map"> <area class="interactive" shape="poly" coords="你的坐标值" href="#"> <area class="misc" shape="poly" coords="你的坐标值" href="#"> </map>
.img-container { position: relative; display: inline-block; } .hover-img { position: absolute; top: 0; left: 0; opacity: 0; transition: opacity 0.2s; } /* 利用:focus-within兼容多数浏览器的area悬停触发 */ .interactive:focus-within ~ .img-container .interactive-img, .misc:focus-within ~ .img-container .misc-img { opacity: 1; } /* 补充hover触发规则,覆盖更多场景 */ .interactive:hover ~ .img-container .interactive-img, .misc:hover ~ .img-container .misc-img { opacity: 1; }
关键注意事项
- 确保所有图片尺寸完全一致,避免切换时出现错位
- 使用jQuery时,需确保页面已引入jQuery库
- CSS方法中,
<area>的href属性不能省略(即使设为空值),否则部分浏览器无法触发hover/focus事件
内容的提问来源于stack exchange,提问作者sammy oster
相关产品推荐
相关产品推荐

