如何用纯CSS让指定图片区域不触发父级<a>标签的跳转?
问题
现有如下简化的HTML和CSS代码:
CSS代码
div { border: 2px solid red; width: 200px; height: 200px; } img { z-index: 0; } #plate { position: absolute; left: 20px; top: 30px; opacity: 0.7; z-index: 10; }
HTML代码
<div> <a href="https://google.com"> <img src="https://placehold.it/200/333333" /> <img id="plate" src="https://placehold.it/100/999999" /> </a> </div>
需求:修改CSS代码,使id为plate的图片区域不可点击(不触发<a>的href跳转),同时<a>标签的其余区域仍保持可点击状态。
解决方案
只需在#plate的CSS规则中添加pointer-events: none;属性即可,修改后的CSS代码如下:
div { border: 2px solid red; width: 200px; height: 200px; } img { z-index: 0; } #plate { position: absolute; left: 20px; top: 30px; opacity: 0.7; z-index: 10; pointer-events: none; /* 新增属性,禁用鼠标事件 */ }
原理说明
pointer-events: none;会让目标元素完全不响应任何鼠标交互事件,点击#plate区域时,鼠标事件会直接穿透到下方元素,不会触发父级<a>的跳转行为;而<a>标签内的其他区域(如底层的200x200图片)依然可以正常响应点击,触发跳转。
内容的提问来源于stack exchange,提问作者Haradzieniec
相关产品推荐
相关产品推荐

