2020-06-29

      **跨浏览器的事件处理程序(各种浏览器均可兼容)**

面试必备@

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>跨浏览器事件处理程序</title>
</head>
    <body>
     <button id="mybtn">点击我</button>
     <script type="text/javascript">
         //兼容所有浏览器
         //addEventLister attachEvent
         var EventUtil = {
             addHandler: function (element,type,handler){
                 //绑定事件
                 //chrome ,firefox,IE9等,addEventLister
                 //IE8及IE8以下的浏览器  attachEvent
                 if (element.addEventListener){
                     element.addEventListener(type,handler,false);
                 }else if(element.attachEvent){
                     element.attachEvent("on",type,handler);
                 }else {
                     element["on"+type]=null
                 }
         },
             removeHandler : function (element,type,handler) {
                 //移除事件
                 //chrome ,firefox,IE9等,addEventLister
                 //IE8及IE8以下的浏览器  detachEvent
                 if(element.removeEventListener){
                     element.removeEventListener
                 }else if(element.detachEvent){
                     element.detachEvent("on",type,handler);
                 }else{
                     element["on"+type]=null
                 }
           }
         }
         var btn=document.getElementById("mybtn");
         var handler =function () {
             alert("Clicked");
         }
         EventUtil.addHandler(btn,"click",handler);
     </script>
   </body>
</html>
上一篇:轻量级前端路由 router directorjs兼容ie8


下一篇:解决ie8 input 垂直方向默认不居中,ie8下placeholder失效