javascript - 如何防止孙子元素的超链接
问题描述
如何在不转到http://example.com页面的情况下使.no-click
div可点击?谁能帮我吗?
这是一个示例https://lajumate.ro/这是带有广告的网页,如果您将鼠标悬停在广告上,则会显示共享按钮和保存按钮,并且它s clickable (the button
位于 href 内)
.test {
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
.no-click {
position: absolute;
top: 25%;
right: 25%;
width: 50px;
height: 50px;
background-color: blue;
}
<a href="http://example.com">
<div class="test">
<div class="no-click">
</div>
</div>
</a>
解决方案
正确的方法是使用stopPropagation
,这是其历史别名的一种较新的方法cancelBubble
,并取消事件冒泡。
在某些情况下preventDefault
可以工作,但请注意,它不会取消冒泡,但可以产生类似的效果。
更新:除非它也与preventDefault
. 稍后会看看,看看为什么会这样。
堆栈片段
var no_click = document.querySelector('.no-click');
no_click.addEventListener('click', function(e) {
e.stopPropagation();
e.preventDefault(); //temp. update, though this should NOT be needed
console.log('hey');
})
.test {
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
.no-click {
position: absolute;
top: 25%;
right: 25%;
width: 50px;
height: 50px;
background-color: blue;
}
<a href="https://example.com">
<div class="test">
<div class="no-click">
</div>
</div>
</a>
推荐阅读
- python - 在将日期与列表进行比较时,用更有效的方法替换 for 循环
- java - Maven - Docker java.lang.NoClassDefFoundError: org/apache/http/client/methods/HttpUriRequest
- scala - 如何在 Scala 中对两列进行字符串连接,但按字母顺序对结果列进行排序?
- python - H2OFrame 列到数组:最快的方法?
- ios - 在特定时间从 UserDefaults 中删除保存的数据?
- sql - SQL server 从周数和年份检索周开始日期和周结束日期
- java - PDFBox - 从 Java 刷新嵌套的 PDComboBox
- javascript - JavaScript 中的持久暗模式
- java - Remove string after second colon in Java
- spring - 春季 5.2.8 中的 log4j xml 配置