zoukankan      html  css  js  c++  java
  • DOM——DOM2级事件的兼容处理

    DOM2级事件的兼容处理(bind、unbind、on、off、run)->this、重复、顺序

    function bind(ele,type,handler){
    	if(ele.addEventListener){
    		ele.addEventListener(type,handler,false);
    	}else if(ele.attachEvent){
    		
    		if(!ele["aBind"+type]){//此数组只创建一次
    			ele["aBind"+type]=[];	//此数组定义的技巧:以aBind为前缀,以type为区分符。可以最大可能的避免重名属性,还可以为每一个事件类型都定义一个数组
    		}
    		var a=ele["aBind"+type];
    		for(var i=0;i<a.length;i++){//避免重复
    			if(a[i].photo==handler)return;	
    		}
    		var tempFn=function(){handler.call(ele)}
    		tempFn.photo=handler;//给“做手术”加一个识别符
    		a.push(tempFn);//放到数组里
    		ele.attachEvent("on"+type,tempFn);//绑定到事件上
    	}
    }
    
    function unbind(ele,type,handler){
    	if(ele.removeEventListener){
    		ele.removeEventListener(type,handler,false);
    	}else if(ele.detachEvent){
    		var a=ele["aBind"+type];
    		if(a){
    			for(var i=0;i<a.length;i++){
    				if(a[i].photo==handler){
    					ele.detachEvent("on"+type,a[i]);
    					a.splice(i,1);	
    				}
    			}
    			
    		}
    		
    	}
    }
    
    
    
    function on(ele,type,fn){
    	if(!ele["aEvent"+type]){
    		ele["aEvent"+type]=[];
    	}	
    	var a=ele["aEvent"+type];
    	for(var i=0;i<a.length;i++){
    		if(a[i]==fn)return;	
    	}
    	a.push(fn);
    	bind(ele,type,run);
    }
    
    function run(e){
    	e=e||window.event;
    	var a=this["aEvent"+e.type];
    	if(a){
    		if(!e.target){
    			e.target=e.srcElement;
    			e.pageX=(document.documentElement.scrollLeft||document.body.scrollLeft)+e.clientX;
    			e.pageY=(document.documentElement.scrollTop||document.body.scrollTop)+e.clientY;
    			e.preventDefault=function(){e.returnValue=false;}
    			e.stopPropagation=function(){e.cancelBubble=true;}
    		}
    		for(var i=0;i<a.length;i++){
    			if(typeof a[i]=="function"){
    				a[i].call(this,e);	
    			}else{
    				a.splice(i,1);
    				i--;	
    			}
    		}
    	}
    }
    
    function off(ele,type,fn){
    	var a=ele["aEvent"+type];
    	if(a){
    		for(var i=0;i<a.length;i++){
    			if(a[i]==fn){
    				
    				a[i]=null;
    				return;
    			}
    		}
    	}
    }
    
    function processThis(obj,fn){
    	return function(e){fn.call(obj,e);}	
    }
    

      

  • 相关阅读:
    Linux 相关scsi命令
    存储
    Multipath多路径冗余全解析
    Oracle中alter system命令参数之scope
    scipy安装失败
    font
    查看端口占用
    oracle参数优化
    组播
    sql给整数补零
  • 原文地址:https://www.cnblogs.com/cataway/p/4985147.html
Copyright © 2011-2022 走看看