IE的事件流叫作事件冒泡,即事件開始由最具體的元素接收,而後逐級向上傳播到較爲不具體的節點。
html
事件捕獲是由最不具體的節點開始接收,逐級向下傳播到較具體的節點dom
「DOM2級事件」規定的事件流包括三個階段: 事件捕獲階段、處於目標階段和事件冒泡階段。函數
對於「事件處理程序過多」問題的解決方案就是事件委託,事件委託利用了事件冒泡,指定一個事件處理程序,就能夠管理某一類型的全部事件。性能
var EventUtil = { addHandler: function (element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, removeHandler: function (element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } }, getEvent: function (event) { return event ? event : window.event; }, getTarget: function (event) { return event.target || event.srcElement; }, preventDefault: function (event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }, stopPropagation: function (event) { if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubbles = true; } }, getRelatedTarget: function (event) { if (event.relatedTarger) { return event.relatedTarget; } else if (event.toElement) { return event.toElement; } else if (event.fromElement) { return event.fromElement; } else { return null; } } };
委託事件實例code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul id="myLinks"> <li id="doSomething">do something</li> <li id="baidu">打開百度</li> <li id="hello"> hello</li> </ul> </body> <script> var EventUtil = {...}; var list = document.getElementById('myLinks'); EventUtil.addHandler(list, "click", function (event) { event = EventUtil.getEvent(event); var target = EventUtil.getTarget(event); switch (target.id) { case "doSomething": document.title = "i changed the document"; break; case "baidu": location.href = 'https://www.baidu.com'; break; case "hello": alert("hello"); break; } }) </script> </html>
最適合事件委託技術的事件包括click,mousedown,mouseup,keydown,keyup,keypress。htm