什么是事件委托/事件代理
利用事件的冒泡傳播機制(觸發當前元素的某一個行為,它父級所有元素的相關行為都會被觸發),如果一個容器中有很多元素都要綁定點擊事件,我們沒有必要一個個的綁定了,只需要給最外層容器綁定一個點擊事件即可,在這個方法執行的時候,通過事件源的區分來進行不同的操作。
具體小案例如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; font-size:14px; } html,body{ width:100%; height:100%; overflow:hidden; } #box{ position:absolute; left:50%; top:50px; width:100px; height:30px; margin-left:-50px; line-height:30px; text-align:center; border:1px solid #2489cc; } #mark{ position:absolute; top:30px; left:-1px; width:300px; height:100px; line-height:100px; text-align:center; background:#ffe470; border:1px solid #2489cc; } </style></head><body> <div id='box'> <span>購物車</span> <div id="mark" style='display:none'> 查看購物車的詳細信息 </div> </div> <script> var mark = document.getElementById('mark'); document.body.onclick = function(e){ e = e || window.event; e.target = e.target || e.srcElement; //如果點擊的是box或者是#box下的span,我們判斷mark是否顯示,顯示讓其隱藏,反之讓其顯示 if(e.target.id==="box" || (e.target.tagName.toLowerCase()==="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></body></html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答