即使使用stopPropagation,事件也会向父母冒泡?

时间:2016-03-27 23:50:14

标签: javascript event-bubbling stoppropagation event-propagation

停止传播是不是要停止冒泡到父元素?

我知道在这种情况下要检查事件目标,我只是想知道为什么stopPropagation,这个单词本身就是防止这个问题,并没有这样做。

https://jsfiddle.net/hzo9eq9m/

var child = document.querySelector('.parent')
    .addEventListener('click',function(e){
        e.stopPropagation();
        $(this.querySelector('.child')).toggleClass('selected');
        console.log(e);
    },
false);
.society {
  padding:10px;
  background-color:green;
  position:relative;
}

.parent {
  background-color:red;
  width:60%;
  margin-left:30%;
}

.child {
  width: 100%;
  background-color:pink;
  position:absolute;
  top:0;
  left:0;
  width:0;
  max-width:0px;
  max-height:0px;
  transition: max-width 1s, max-height 1s;
  overflow:hidden;
}

.child.selected {
  top:0;
  left:0;
  width:100%;
  max-width:1000px;
  max-height:1000px;
}
<div class="society">
  <div class="parent">
     parent
    <div class="child">
      child
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

如果您想阻止点击.child传播,则必须在click上绑定.child处理程序:

document.getElementById('parent').addEventListener('click', function(e) {
  alert('parent');
}, false);

document.getElementById('child').addEventListener('click', function(e) {
  alert('child');
  e.stopPropagation(); // if this isn't called, you'll get 2 alerts when clicking on #child
}, false);
#parent { background-color: yellow; }

#child { background-color: red; }
<div id="parent">
  Parent
  <div id="child">
    Child
  </div>
</div>

答案 1 :(得分:0)

是的,这正是它的作用!

您的代码会侦听具有父类的元素的单击,并使用子类在所有元素上切换选定的类。这不是意图吗?

如果您使用stopPropagation为子项添加事件,则不会触发父点击:

var parent = document.querySelector('.parent').addEventListener('click',function(e){
    e.stopPropagation();
  $(this.querySelector('.child')).toggleClass('selected');
  console.log(e);
},false);
var child = document.querySelector('.child').addEventListener('click',function(e){
    e.stopPropagation();
  $(this).toggleClass('selected');
  console.log(e);
},false);