其他分享
首页 > 其他分享> > 2020-06-29

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>

标签:IE8,06,29,attachEvent,element,handler,2020,浏览器,type
来源: https://blog.csdn.net/qq_46356186/article/details/107031035