1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 9 </body> 10 <script type="text/javascript"> 11 // 事件綁定的兼容寫法 12 // 綁定事件 13 // 參數說明:element元素,type事件類型,handle函數 14 function addEventFn(element, type, handle){ 15 if(window.addEventListener){ 16 element.addEventListener(type, handle, false); 17 }else if(window.attachEvent){ 18 element.attachEvent("on"+type, handle); 19 }else{ 20 element["on"+type] = handle; 21 } 22 } 23 // 移除事件 24 function removeEventFn(element, type, handle){ 25 if(window.removeEventListener){ 26 element.removeEventListener(type, handle, false); 27 }else if(window.detachEvent){ 28 element.detachEvent("on"+type, handle); 29 }else{ 30 element["on"+type] = null; 31 } 32 } 33 //********************for example***************** 34 addEventFn(document, "click", function(){ 35 alert("測試兼容方法"); 36 }); 37 </script> 38 </html>