Skip to content

ES6 - 图像映射

ES6 - 使用 JavaScript 创建交互式图像映射

Section titled “ES6 - 使用 JavaScript 创建交互式图像映射”

客户端图像映射 (Client-side image maps) 允许您在图像上定义可点击区域。虽然 HTML 通过 <map> 和 <area> 标签提供了基本结构,但可以使用 JavaScript 来增强它们的交互性,使其超越简单的导航。本节探讨如何将 HTML 图像映射与现代 JavaScript 事件处理相结合。

核心 HTML 结构包括一个带有 usemap 属性的 <img> 标签,该属性指向一个 <map> 元素。<map> 元素由其 name 属性标识(与 usemap 值匹配,前面带一个 ’#’),包含多个 <area> 标签。每个 <area> 标签使用 shape(例如,rect、circle、poly)和 coords 属性定义一个可点击区域。

现代 JavaScript 实践,如使用 addEventListener 进行事件处理,以及使用 document.querySelector 或 document.getElementById 进行 DOM 操作,比旧式的内联事件处理程序(如 onmouseover)和直接表单访问更受欢迎。

以下示例演示了如何使用 JavaScript 在鼠标悬停在图像映射的不同部分时显示信息。我们将使用 data-* 属性在 <area> 元素上存储信息。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Image Map Demo</title>
<style>
#infoDisplay {
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
min-height: 20px;
}
</style>
</head>
<body>
<h2>Interactive Image Map</h2>
<p>Hover over the shapes in the image below:</p>
<!-- Replace with your actual image path -->
<img src="https://via.placeholder.com/300x200.png?text=Sample+Image+Map"
alt="Sample Interactive Map"
usemap="#tutorialsMap"
style="border:1px solid black;">
<map name="tutorialsMap">
<area shape="rect" coords="25,25,125,75" href="#"
data-info="Rectangle Area: Learn about HTML" alt="HTML Area">
<area shape="circle" coords="100,150,40" href="#"
data-info="Circle Area: Explore CSS" alt="CSS Area">
<area shape="poly" coords="175,25,275,25,225,100" href="#"
data-info="Polygon Area: Discover JavaScript" alt="JavaScript Area">
</map>
<div id="infoDisplay">Hover over an area to see details.</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const infoDisplay = document.getElementById('infoDisplay');
const areas = document.querySelectorAll('map[name="tutorialsMap"] area');
areas.forEach(area => {
area.addEventListener('mouseover', () => {
infoDisplay.textContent = area.dataset.info || 'Hovering over ' + area.alt;
});
area.addEventListener('mouseout', () => {
infoDisplay.textContent = 'Hover over an area to see details.';
});
// Example: Handle click events
area.addEventListener('click', (event) => {
// Prevent navigation if href is just '#'
if (area.getAttribute('href') === '#') {
event.preventDefault();
}
alert(`You clicked on: ${area.dataset.info || area.alt}`);
// You could also navigate or perform other actions here
// For example: window.location.href = 'some_page.html';
});
});
});
</script>
</body>
</html>

在浏览器中运行此 HTML 文件时:

  1. 将显示一张图像(本例中为占位符)。
  2. 当您将鼠标光标移到图像上定义的矩形、圆形或多边形区域时,图像下方 div 中(id="infoDisplay")的文本将更新,显示悬停区域的 data-info 属性。
  3. 当鼠标移出某个区域时,div 中的文本将恢复为默认消息。
  4. 点击任何区域将触发一个弹窗 (alert box),显示该区域的信息。

虽然 HTML 图像映射仍然受支持,但对于更复杂的交互式图形,请考虑使用可伸缩矢量图形 (SVG) 或 HTML Canvas API。这些技术提供了更大的灵活性、更复杂的事件处理,并且通常更易于访问和响应。然而,对于像上述示例这样的简单用例,图像映射仍然是一个直接的解决方案。