如何让链接仅作用于嵌套div的父元素,不触发子label元素跳转?
解决方案
方法1:纯CSS实现(推荐)
核心思路是调整hover触发的挂载节点,同时禁用label区域的点击事件透传,不需要修改JS逻辑:
- 将hover触发逻辑从
.label本身移到父级.button元素上,避免label禁用交互后hover效果失效 - 给
.label添加pointer-events: none属性,点击该区域时不会触发任何交互事件,自然不会触发父级a标签的跳转
修改后的完整CSS代码如下:
@keyframes show-label { from { opacity: 0%; } to { opacity: 100%; } } body { display: flex; flex-direction: column; flex: auto; align-items: center; } div.button { display: flex; flex-direction: column; justify-content: flex-end; flex: auto; width: 20vw; height: 20vw; background-color: lightgray; border-radius: 10px; } .label { opacity: 0%; /* 新增:禁用该区域的所有点击交互 */ pointer-events: none; } /* 修改:hover按钮时显示label,不再依赖label自身的hover */ .button:hover .label { animation: show-label 500ms forwards; } div.label { background-color: rgba(0, 0, 0, 0.5); border-radius: 0px 0px 10px 10px; } p.label { color: white; font-size: min(1.8vw, 18.17px); text-align: center; }
同时修正原HTML代码中的笔误(p标签class属性缺少等号):
<html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <a href="#"> <div class="button" style="max-width: 157.39px; max-height: 157.39px;"> <div class="label"> <p class="label">the big</p> </div> </div> </a> </body> </html>
方法2:JavaScript实现
如果不想调整现有CSS逻辑,可以通过阻止label元素的点击事件冒泡实现,在页面中添加如下JS代码即可:
document.querySelectorAll('.label').forEach(label => { label.addEventListener('click', e => { // 阻止事件冒泡到父级a标签 e.stopPropagation(); // 阻止默认跳转行为 e.preventDefault(); }) })
两种方案都可以实现点击按钮非label区域正常跳转,点击label区域不触发跳转的效果。
内容的提问来源于stack exchange,提问作者grem
相关产品推荐
相关产品推荐

