事件绑定 跨浏览器
Posted halo-漾
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了事件绑定 跨浏览器相关的知识,希望对你有一定的参考价值。
if(document.addEventListener){ this.addEvent = function(elem,type,fn){ elem.addEventListener(type,fn,false); return fn; }; this.removeEvent = function(elem,type,fn){ elem.removeEventListener(type,fn,false); }; }else if(document.attachEvent){ this.addEvent = function(elem,type,fn){ var bound = function(){ return fn.apply(elem,arguments); }; elem.attachEvent("on" + type,bound); return bound; }; this.removeEvent = function(elem,type,fn){ elem.detachEvent("on" + type,fn); }; }
//用法
addEvent(window,"load",function(){
var elems = document.getElementsByTagName("div");
alert(elems.length);
for(var i = 0; i < elems.length; i++)(function(elem){
var handler = addEvent(elem,"click",function(){
this.style.backgroundColor = this.style.backgroundColor == "" ? "green" : "";
removeEvent(elem,"click",handler);
});
})(elems[i]);
});
以上是关于事件绑定 跨浏览器的主要内容,如果未能解决你的问题,请参考以下文章