1、什么是事件的委托/事件代理
利用了事件的冒泡传播机制(触发当前元素的某个行为,它父级所有元素的相关行为都会被触发),如果一个容器中有很多元素都要绑定点击事件,我们没有必要一个个的绑定了,只需要给最外层的容器绑定一个点击事件即可,在这个方法执行的时候,通过事件源的区分来进行不同的操作;
案例:
body, div, span { margin: 0; padding: 0; font-size: 14px; } html, body { width: 100%; height: 100%; overflow: hidden; } #box { position: absolute; left: 50%; top: 51px; width: 100px; height: 30px; margin-left: -50px; line-height: 30px; text-align: center; border: 1px solid #2489ce; } #mark { position: absolute; top: 30px; left: -1px; width: 300px; height: 100px; line-height: 100px; text-align: center; background-color: lightyellow; border: 1px solid #2489ce; }
<div id="box"> <span>购物车</span> <div id="mark" style="display: none;">查看购物车中的详细信息</div> </div> <script type="text/javascript"> var box = document.getElementById('box'); var mark = document.getElementById('mark'); document.body.onclick = function (e) { e = e || window.event; e.target = e.target || e.srcElement; //如果点击的是box或者是box下的span,我们判断,ark是否显现,或者隐藏 if(e.target.id === 'box' || e.target.tagName.toLocaleLowerCase() === "span" && e.target.parentNode.id === "box"){ if(mark.style.display === 'none'){ mark.style.display = 'block'; }else { mark.style.display = 'none'; } return; } //如果事件源是#mark,不进行任何的操作 if(e.target.id === 'mark'){ return; } //以上都不是的话,我们直接隐藏 mark.style.display = 'none'; } </script>