首页 > 解决方案 > 如何防止孙子元素的超链接

问题描述

如何在不转到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>

标签: javascriptjqueryhtmlcsshyperlink

解决方案


正确的方法是使用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>


推荐阅读