在用户单击图像的某个区域后更改元素的CSS样式



区域是使用map标记定义的。图片上方还有一段文字。当用户点击图像区域时,段落的颜色会发生变化。知道如何用javascript做这件事吗?

例如,这是html

<html>
<body>
<h1>The map and area elements</h1>
<p>Click on the area of the image, there will be several areas. When click, the color will change depending on the area that was clicked.</p>
<img src="theimage.jpg" alt="image" usemap="#theimage" width="400" height="379">
<map name="theimage">
<area shape="rect" coords="34,44,270,350" alt="thearea" href="">
</map>
</body>
</html>

要在单击具有<area>标记坐标的区域时更改<p>标记的样式,请对click事件使用常见的addEventListener事件侦听器。

此外,当使用event.preventDefault()单击标记<area>时,您需要进行委派以防止默认行为。

let paragraph = document.querySelector("p");
let area = document.querySelector("area");
area.addEventListener("click", function (event) {
event.preventDefault();
paragraph.style.color = "green";
});
<h1>The map and area elements</h1>
<p>Click on the area of the image, there will be several areas. When click, the color will change depending on the area that was clicked.</p>
<img src="https://st.depositphotos.com/1428083/2946/i/600/depositphotos_29460297-stock-photo-bird-cage.jpg" alt="image" usemap="#theimage" width="400" height="379" />
<map name="theimage">
<area shape="rect" coords="34,44,270,350" alt="thearea" href="" />
</map>

试试这个代码,这会很好

window.addEventListener('load',()=>{
let my_image=document.querySelector('.my-image');
let para=document.querySelector('p');
my_image.addEventListener('click',()=>{
para.style.color='blue';
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tutorial</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>The map and area elements</h1>
<p>Click on the area of the image, there will be several areas. When click, the color will change depending on the area that was clicked.</p>
<img
src="theimage.jpg"
alt="Workplace"
usemap="#workmap"
width="400"
height="379"
/>
<map name="workmap">
<area
shape="rect"
coords="34,44,270,350"
alt="Computer"
class="my-image"
/>

</map>
<script src="script.js"></script>
</body>
</html>

最新更新