想要相容IE678,少用原型,因為它們沒有完全實現ECMA-262規範 測試代碼 ...
想要相容IE678,少用原型,因為它們沒有完全實現ECMA-262規範
1 (function(window){ 2 //相容IE678時少用原型,因為它沒有完全遵循ECMA-262規範 3 4 //襯墊代碼:isArray方法的相容方案 5 if (!Array.isArray) { 6 Array.isArray = function(arg) { 7 return Object.prototype.toString.call(arg) === '[object Array]'; 8 }; 9 } 10 11 //襯墊代碼:every數組過濾方法的相容方案 12 if (!Array.prototype.every){ 13 Array.prototype.every = function(fun /*, thisArg */) 14 { 15 'use strict'; 16 17 if (this === void 0 || this === null) 18 throw new TypeError(); 19 20 var t = Object(this); 21 var len = t.length >>> 0; 22 if (typeof fun !== 'function') 23 throw new TypeError(); 24 25 var thisArg = arguments.length >= 2 ? arguments[1] : void 0; 26 for (var i = 0; i < len; i++) 27 { 28 if (i in t && !fun.call(thisArg, t[i], i, t)) 29 return false; 30 } 31 32 return true; 33 }; 34 } 35 36 var bear = { 37 //該函數是一個全相容的事件綁定函數,但只能處理一個事件回調函數 38 addListener: function(node,name,fn){ 39 if(node.addEventListener){ 40 node.addEventListener(name,fn); 41 }else{ 42 node.attachEvent("on"+name,function(){ 43 fn.call(node); 44 }) 45 } 46 }, 47 48 //該函數是一個全相容的事件綁定函數,能處理一個回調數組 49 addMoreListener: function(node,name,arr){ 50 if(typeof arr === "function"){ 51 bear.addListener(node,name,arr); 52 }else if(Array.isArray(arr)&&arr.length){ 53 if(node.addEventListener){ 54 55 }else if(node.attachEvent){ 56 arr = arr.reverse(); 57 } 58 var flag = arr.every(function(item){ 59 return typeof item === "function"; 60 }) 61 if(flag){ 62 for(var i=0;i<arr.length;i++){ 63 bear.addListener(node,name,arr[i]); 64 } 65 }else{ 66 throw new Error("數組內元素類型有誤"); 67 } 68 }else{ 69 throw new Error("第三參數類型有誤或為空數組"); 70 } 71 } 72 } 73 74 window.bear = bear; 75 })(window)
測試代碼
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 #app{ 12 width: 100px; 13 height: 100px; 14 background: #F4A460; 15 position: absolute; 16 left: 0; 17 right: 0; 18 bottom: 0; 19 top: 0; 20 margin: auto; 21 font: 20px/100px helvetica; 22 text-align: center; 23 24 } 25 </style> 26 27 28 <script src="./js/bear-extend-event2.js"></script> 29 <script> 30 window.onload = function(){ 31 32 var appNode = document.getElementById("app"); 33 var arr = [function(){console.log(1);},function(){console.log(2);}] 34 //debugger 35 bear.addMoreListener(appNode,"click",arr); 36 } 37 </script> 38 </head> 39 <body> 40 <div id="app">app</div> 41 </body> 42 </html>