事件对象
什么是事件对象?
在触发DOM上的事件时都会产生一个对象。
事件对象event
1.DOM中的事件对象
(1) ype属性用于获取事件类型
(2) arget属性用于获取事件目标
(3)stopPropagation()方法用于阻止事件冒泡
(4)preventDefault()方法用于阻止事件的默认行为
2.IE中的事件对象
(1) ype属性用于获取事件类型
(2)srcElement属性 用于获取事件目标
(3)cancelBubble属性 true阻止事件冒泡
(4) eturnValue属性 false阻止事件的默认行为
封装函数eventUtil():
var eventUtil = { getEvent:function (event) { return event?event:window.event; }, getType: function (event) { return event.type; }, getTarget:function (event) { return event.target||event.srcElement; }, //阻止冒泡 stopPropagation:function (event) { if(event.stopPropagation){ event.stopPropagation(); }else { event.cancelBubble=true; } }, //阻止事件默认行为; preventDefault:function(event){ if(event.preventDefault){ event.preventDefault(); }else { event.returnValue = false; } }, //添加具柄; 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; } } };
示例:
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="eventUtil.js"></script> <script src="test1.js"></script> </head> <body> <div id="div"> <input type="button" value="click1" id="btn1"> <a href="https://www.baidu.com" id="a">百度</a> </div> </body> </html>
js:
window.onload = function () { var btn1 = document.getElementById("btn1"); var a = document.getElementById("a"); var div = document.getElementById("div"); function show() { alert("btn clicked"); } eventUtil.addHandler(div,"click",function () { alert("我是父盒子"); }); eventUtil.addHandler(btn1,"click",show); eventUtil.addHandler(a,"click",function (e) { e = eventUtil.getEvent(e); alert(eventUtil.getTarget(e)); eventUtil.stopPropagation(e); eventUtil.preventDefault(e); }); eventUtil.removeHandler(btn1,"click",show); };