首页 > 其他 > 详细

DOM事件流与事件委托

时间:2021-07-29 00:55:52      阅读:22      评论:0      收藏:0      [点我收藏+]

事件流

<style>
  .big{
    width: 300px;
    height: 300px;
    background-color: red;
  }
  .center{
    width: 200px;
    height: 200px;
    background-color: yellow;
  }
  .small{
    width: 100px;
    height: 100px;
    background-color: blue;
  }
</style>
<div class="big">
    <div class="center">
        <div class="small"></div>
    </div>
</div>
  let big = document.querySelector(".big")
  let center = document.querySelector(".center")
  let small = document.querySelector(".small")
  big.onclick = function(){
    console.log("我是big")
  }
  center.onclick = function(){
    console.log("我是center")
  }
  small.onclick = function(){
    console.log("我是small")
  }

  // 顺序是 small-center-big
  // 从里到外是事件冒泡(默认事件在这个阶段触发)
  // 从外到里是事件捕获

<ul>
  <li>香蕉</li>
  <li>苹果</li>
  <li>鸭梨</li>
</ul>
// 利用事件委托来实现删除
  let ul = document.querySelector("ul")
  ul.onclick = function(e){
    ul.removeChild(e.target)
  }

将事件委托给父元素,利用事件冒泡,可以不用给每个子元素都绑定事件

DOM事件流与事件委托

原文:https://www.cnblogs.com/duet/p/15073095.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!