你的位置:首页 > Java教程

[Java教程]跨浏览器的事件侦听器和事件对象


今天特意为跨浏览器实现添加事件侦听器和跨浏览器事件对象的使用方法做了下总结,并把这些方法打包。

打包的一个EventUtil对象

 1   EventUtil = { 2     // 添加侦听事件 3     addEventListener:function (element, type, handler) { 4       // IE9+、Firefox、Safari、chrome和Opera 5       if(typeof element.addEventListener == "function") { 6         element.addEventListener(type, handler, false); 7       } 8       // IE8- 9       else if(typeof element.attachEvent == "function") {10         element.attachEvent("on" + type, handler);11       }12     },13     14     // 移除侦听事件15     removeEventListener:function (element, type, handler) {16       // IE9+、Firefox、Safari、chrome和Opera17       if(typeof element.addEventListener == "function") {18         element.removeEventListener(type, handler, false);19       }20       // IE8-21       else if(typeof element.attachEvent == "function") {22         element.detachEvent("on" + type, handler);23       }24     },25     26     // 获取事件对象27     getEvent:function(event) {28       if(typeof event == "undefined") {29         event = window.event; // IE浏览器30       }31       return event;32     },33     34     // 获取触发事件的元素35     getTarget:function(event){36       if(typeof event.srcElement == "undefined") {37         return event.target;38       }else {39         return event.srcElement; // IE浏览器40       }41     },42     43     // 获取事件类型44     getType:function(event) {45       return event.type;46     },47     48     // 阻止事件的默认行为49     preventDefault:function(event) {50       if(event.preventDefault){51         event.preventDefault();52       }else {53         event.returnValue = false; // IE浏览器54       }55     },56     57     // 阻止事件冒泡58     stopPropagation:function(event) {59       if(typeof event.cancelBubble == "undefined") {60         event.stopPropagation();61       }else {62         event.cancelBubble = true; // IE浏览器63       }64     }65   };  

测试代码

1   <div id="box" style="color:red;width: 100%;height:200px;" >2     <input type="button" value="点击" id="btn" />3   </div>4   <a href="http://www.test.com" id="a">test</a>

 1   var box = document.querySelector("#box"); 2   box.onclick = function(event) { 3     event = EventUtil.getEvent(event); 4     alert(EventUtil.getType(event)); 5     alert(EventUtil.getTarget(event)); 6   }; 7   var input = document.querySelector("input"); 8   input.onclick = function(event) { 9     event = EventUtil.getEvent(event);10     EventUtil.stopPropagation(event);11   };12   13   var a = document.getElementById("a");14   a.onclick = function(event) {15     event = EventUtil.getEvent(event);16     EventUtil.preventDefault(event);17   };