IE兼容事件绑定V1.0

时间:2023-03-09 08:26:57
IE兼容事件绑定V1.0

想要兼容IE678,少用原型,因为它们没有完全实现ECMA-262规范

 (function(window){
//兼容IE678时少用原型,因为它没有完全遵循ECMA-262规范 //衬垫代码:isArray方法的兼容方案
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
} //衬垫代码:every数组过滤方法的兼容方案
if (!Array.prototype.every){
Array.prototype.every = function(fun /*, thisArg */)
{
'use strict'; if (this === void 0 || this === null)
throw new TypeError(); var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function')
throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
if (i in t && !fun.call(thisArg, t[i], i, t))
return false;
} return true;
};
} var bear = {
//该函数是一个全兼容的事件绑定函数,但只能处理一个事件回调函数
addListener: function(node,name,fn){
if(node.addEventListener){
node.addEventListener(name,fn);
}else{
node.attachEvent("on"+name,function(){
fn.call(node);
})
}
}, //该函数是一个全兼容的事件绑定函数,能处理一个回调数组
addMoreListener: function(node,name,arr){
if(typeof arr === "function"){
bear.addListener(node,name,arr);
}else if(Array.isArray(arr)&&arr.length){
if(node.addEventListener){ }else if(node.attachEvent){
arr = arr.reverse();
}
var flag = arr.every(function(item){
return typeof item === "function";
})
if(flag){
for(var i=0;i<arr.length;i++){
bear.addListener(node,name,arr[i]);
}
}else{
throw new Error("数组内元素类型有误");
}
}else{
throw new Error("第三参数类型有误或为空数组");
}
}
} window.bear = bear;
})(window)

测试代码

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
#app{
width: 100px;
height: 100px;
background: #F4A460;
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
font: 20px/100px helvetica;
text-align: center; }
</style> <script src="./js/bear-extend-event2.js"></script>
<script>
window.onload = function(){ var appNode = document.getElementById("app");
var arr = [function(){console.log(1);},function(){console.log(2);}]
//debugger
bear.addMoreListener(appNode,"click",arr);
}
</script>
</head>
<body>
<div id="app">app</div>
</body>
</html>