给父级元素定义一个事件(比如 onclick 点击事件)。
父级元素触发这个事件后,就会命令手下的指定元素去完成某些事情。
主要用到的关键字:srcElement 和 target。
献上代码
/* 这里是CSS代码 */
.item, .other { width: 100px; height: 100px; margin: 20px; display: inline-block; font-size: 20px; font-weight: 600; text-align: center; line-height: 100px; color: #fff;}
.item { background-color: darkcyan;}
.other { background-color: brown;}
复制代码
<!-- 这里是HTML代码 -->
<div id="box"> <div class="item">item</div> <div class="item">item</div> <div class="other">other</div> <div class="item">item</div> <div class="item">item</div> <div class="item">item</div> <div class="item">item</div> <div class="item">item</div> <div class="other">other</div> <div class="item">item</div> <div class="item">item</div> <div class="other">other</div> <div class="item">item</div> <div class="item">item</div> <div class="other">other</div> <div class="item">item</div></div>
复制代码
/* 这里是JS代码 */box.onclick = function(e) { var ev = e || event; // 兼容性写法
/* * 兼容性写法 * 老版火狐不兼容 srcElement * 老版IE不兼容 target */ var iTarget = ev.srcElement || ev.target; if(iTarget.className == 'item') { iTarget.style.borderRadius = "50%"; }}
复制代码
上面的例子
首先在 HTML 中定义一个容器 div,id 是 box。
给 box 添加一个 onclick 事件。
当 box 触发 onclick 后,就命令其下 className(类名)为 item 的元素,把 item 的圆角改成 50%。
如果类名不是 item,则不会发生任何事情 。
用事件委托的好处,就是省却写循环。而且攻击范围大,根本不用去想手下有多少个类名为 item 的元素。
如果需要大量修改其下的子元素(比如动画),用事件委托是一个非常不错的选择。
事件委托和事件绑定的区别
事件绑定例子
/* CSS代码 */#box { width: 200px; height: 200px; border: 1px solid cadetblue; margin: 20px; float: left; display: flex; justify-content: center; align-items: center;}
.item { width: 100px; height: 100px; background-color: rgb(100, 149, 237);}
复制代码
<!-- HTML代码 --><div id="box"> <div class="item" id="item"></div></div>
复制代码
/* JS代码 */item.onclick = function() {
if(getComputedStyle(this, false)['backgroundColor'] == 'rgb(100, 149, 237)') { this.style.backgroundColor = 'rgb(147, 112, 219)'; } else { this.style.backgroundColor = 'rgb(100, 149, 237)'; }
this.id = 'test';}
复制代码
可以看到,点击之前,id 是 item,点击之后,id 是 test。
但即使 id 改变了,那个事件依然绑定在该元素上。
上面用到 getComputedStyle 可以参考【JS】获取元素宽度
事件委托例子
/* CSS代码 */
#box { width: 200px; height: 200px; border: 1px solid cadetblue; margin: 20px; float: left; display: flex; justify-content: center; align-items: center;}
.item { width: 100px; height: 100px; background-color: rgb(100, 149, 237);}
复制代码
<!-- HTML代码 -->
<div id="box"> <div class="item" id="item"></div></div>
复制代码
/* JS代码 */
box.onclick = function(e) { var ev = e || event; var iTarget = ev.srcElement || ev.target; if(iTarget.id == 'item') { if(getComputedStyle(iTarget, false)['backgroundColor'] == 'rgb(100, 149, 237)') { iTarget.style.backgroundColor = 'rgb(147, 112, 219)'; } else { iTarget.style.backgroundColor = 'rgb(100, 149, 237)'; }
iTarget.id = 'test'; }}
复制代码
因为事件是委托在 id 为 item 的元素上。当元素的 id 改变了,该事件就找不到指定元素了。
评论