javascript - 最内层元素上的调度事件不会导致向上层元素冒泡?

标签 javascript html dom-events event-bubbling

innerDiv = document.getElementById("inner");
innerDiv.onclick = function(e) {
  console.log("PURPLE COLOR DIV");

}

outterDiv = document.getElementsByClassName("outter")[0];
outterDiv.onclick = function(e) {
  console.log("ORANGE COLOR DIV");
};

containerDiv = document.getElementsByClassName("container")[0];
containerDiv.onclick = function() {
  console.log("RED COLOR DIV");
}

setTimeout(() => document.getElementById("inner").dispatchEvent(new Event('click'), {
  bubbles: true
}), 2000)
.container {
  width: 260px;
  height: 170px;
  background-color: maroon;
  padding-top: 40px;
}

.outter {
  width: 200px;
  height: 80px;
  background: orange;
  margin: 0 auto;
  padding-top: 35px;
}

#inner {
  background: purple;
  width: 100px;
  height: 50px;
  margin: auto;
}
<div class="container">
  <div class="outter">
    <div id="inner"></div>
  </div>
</div>

问题

setTimeout 导致dispatchEvent 触发后,橙色和红色回调不会执行。如果 bubbles 属性设置为 true,为什么会出现这种情况? 如果单击 UI 紫色 div,冒泡会按预期完成其工作。

fiddle 示例:http://jsfiddle.net/0tko5qwe/

最佳答案

您需要将选项添加到 Event() 构造函数本身:

new Event('click', { bubbles: true})

innerDiv = document.getElementById("inner");
innerDiv.onclick = function(e) {
  console.log("PURPLE COLOR DIV");

}

outterDiv = document.getElementsByClassName("outter")[0];
outterDiv.onclick = function(e) {
  console.log("ORANGE COLOR DIV");
};

containerDiv = document.getElementsByClassName("container")[0];
containerDiv.onclick = function() {
  console.log("RED COLOR DIV");
}

setTimeout(() => document.getElementById("inner").dispatchEvent(new Event('click', {
  bubbles: true
})), 500)
.container {
  width: 260px;
  height: 170px;
  background-color: maroon;
  padding-top: 40px;
}

.outter {
  width: 200px;
  height: 80px;
  background: orange;
  margin: 0 auto;
  padding-top: 35px;
}

#inner {
  background: purple;
  width: 100px;
  height: 50px;
  margin: auto;
}
<div class="container">
  <div class="outter">
    <div id="inner"></div>
  </div>
</div>

关于javascript - 最内层元素上的调度事件不会导致向上层元素冒泡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125709/

相关文章:

javascript - 无法使用 imageSource 模块在 Nativescript/Javascript 中保存 URL 中的图像

javascript - React : this. state.renderData.filter 不是一个函数

javascript - 事件调用回调即调用callback

javascript - pg-promise,使用带有嵌套对象的命名参数

jquery - 为什么页面元素、动画、视差加载如此不稳定?

javascript - 有没有办法改变 CSS 调整 Angular 的位置?

php - 如果返回,在 php 中添加 div 类

javascript - 微软边缘: onclick event stops working?

javascript - 使用库在 CoffeeScript 中获取回调

Javascript从窗口顶部滑动不可见的div