Event对象跨浏览器兼容性写法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Event对象跨浏览器兼容性写法</title> </head> <body> <script> 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]=handler; } }, //获取事件本身 getTarget:function (){ return event.target || event.srcElement; }, //阻止默认行为 preventDefault:function (){ if(event.preventDefault){ event.preventDefault(); }else{ event.returnValue=false; } }, //取消冒泡和捕获 stopPropagation:function (){ if(event.stopPropagation){ event.stopPropagation(); }else{ event.cancelBubble=true; } } } </script> <!-- 测试 --> <div id="div"> 爸爸 <button id="btn">儿子</button> </div> <a id="a" href="https://www.baidu.com/">百度</a> <script> var div=document.getElementById("div"); var btn=document.getElementById("btn"); EventUtil.addHandler(div,"click",function(){ console.log("我是老子"); console.log(EventUtil.getTarget(event));//获取target }) EventUtil.addHandler(btn,"click",function(){ console.log("我是儿子"); EventUtil.stopPropagation();//阻止了冒泡 }) var a=document.getElementById("a"); EventUtil.addHandler(a,"click",function(){ console.log("我是链接"); EventUtil.preventDefault();//阻止默认行为 }) </script> </body> </html>
相关推荐
Kakoola 2020-08-01
delmarks 2020-06-28
wanwanwandj 2020-02-24
书虫媛 2020-02-02
bearhoopIT之道 2020-08-16
凯哥Java 2020-07-04
haidaoxianzi 2020-07-04
aNian 2020-06-16
qingjiuquan 2020-06-07
fraternityjava 2020-06-04
明瞳 2020-06-04
HappyHeng 2020-05-28
88473166 2020-05-14
zkwgpp 2020-05-07
oXiaoChong 2020-05-07
ChainDestiny 2020-05-07
doomvsjing 2020-05-07
xuMelon 2020-05-04