如何通过JavaScript鼠标事件在image map图片右侧添加悬停提示框
解决方案
1. 调整HTML结构
给图片和提示框添加容器包裹,同时新增自定义tooltip元素:
<div class="tooltip-container"> <img id="spell-1-sun" src="shm_resources/magic/1-mesomorph-body-unav.png" usemap="#spell-1-sun" border="0" alt="" class="magic-sun-1"> <!-- 自定义悬停提示框 --> <div id="custom-tooltip" class="tooltip">这里替换成你要显示的提示内容</div> </div> <map id="i-spell-1-sun" name="spell-1-sun"> <area shape="poly" coords="0,0,39,1,39,39,0,39" data-passage="Ultimate Test 2" alt="" data-setter="$spellsunone to 'on'" onMouseOver="showTooltip('这里替换成你要显示的提示内容'); if(document.images) document.getElementById('spell-1-sun').src= 'shm_resources/magic/1-mesomorph-body-hover.png';" onMouseOut="hideTooltip(); if(document.images) document.getElementById('spell-1-sun').src= 'shm_resources/magic/1-mesomorph-body-unav.png';" /> </map>
2. 添加CSS样式
通过定位让提示框固定在图片右侧,默认隐藏并添加基础美化:
.tooltip-container { position: relative; display: inline-block; /* 容器宽度适配图片 */ } .tooltip { position: absolute; left: 100%; /* 定位到图片右侧 */ top: 50%; transform: translateY(-50%); /* 垂直居中对齐 */ margin-left: 10px; /* 和图片保持间距 */ padding: 8px 12px; background-color: #2d2d2d; color: #fff; border-radius: 4px; font-size: 14px; white-space: nowrap; /* 避免文字换行 */ display: none; /* 默认隐藏 */ z-index: 1000; } /* 可选:给提示框添加左侧小箭头 */ .tooltip::before { content: ''; position: absolute; right: 100%; top: 50%; transform: translateY(-50%); border: 6px solid transparent; border-right-color: #2d2d2d; }
3. 添加JS控制逻辑
编写简单函数控制提示框的显示、隐藏和内容更新:
function showTooltip(text) { const tooltip = document.getElementById('custom-tooltip'); tooltip.textContent = text; tooltip.style.display = 'block'; } function hideTooltip() { const tooltip = document.getElementById('custom-tooltip'); tooltip.style.display = 'none'; }
核心说明
- 原生
title属性的提示框无法自定义位置,所以用独立DOM元素实现更灵活的定位和样式 - 保留了你原有图片切换的逻辑,不会影响已有的功能
- 如果需要给不同
area设置不同提示内容,只需在showTooltip()中传入对应文本即可
内容的提问来源于stack exchange,提问作者scriptbot
相关产品推荐
相关产品推荐

