最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Capture click event on parent container but not child - Stack Overflow

programmeradmin20浏览0评论

With the following example:

HTML:

<div class="parent" onclick="alert('hello!')">
  <div class="child"></div>
</div>

CSS:

.parent {
  align-items: center;
  background: blue;
  display: flex;
  justify-content: center;
}

.child {
  background: pink;
  height: 100px;
  width: 200px;
}

I want the onclick event to fire when the user clicks on the parent / blue section. But not when the user clicks on the child / pink section. Right now the event fires even when the pink is being clicked, which is of course obvious since the .child is a child of the parent. Is there any way to get past this?

With the following example:

HTML:

<div class="parent" onclick="alert('hello!')">
  <div class="child"></div>
</div>

CSS:

.parent {
  align-items: center;
  background: blue;
  display: flex;
  justify-content: center;
}

.child {
  background: pink;
  height: 100px;
  width: 200px;
}

I want the onclick event to fire when the user clicks on the parent / blue section. But not when the user clicks on the child / pink section. Right now the event fires even when the pink is being clicked, which is of course obvious since the .child is a child of the parent. Is there any way to get past this?

Share Improve this question asked Feb 3, 2017 at 10:52 user818700user818700 1
  • Possible duplicate of How can I stop an onclick event from firing for parent element when child is clicked? – evolutionxbox Commented Feb 3, 2017 at 10:58
Add a comment  | 

2 Answers 2

Reset to default 16

Use event.stopPropagation() method to event bubbling up to the DOM tree.

.parent {
  align-items: center;
  background: blue;
  display: flex;
  justify-content: center;
}
.child {
  background: pink;
  height: 100px;
  width: 200px;
}
<div class="parent" onclick="alert('hello!')">
  <div class="child" onclick="event.stopPropagation()"></div>
</div>

You have to use .stopPropagation() for that event.

.parent {
  align-items: center;
  background: blue;
  display: flex;
  justify-content: center;
}
.child {
  background: pink;
  height: 100px;
  width: 200px;
}
<div class="parent" onclick="alert('I am parent')">
  <div class="child" onclick="event.stopPropagation()"></div>
</div>

发布评论

评论列表(0)

  1. 暂无评论