WEB开发网
开发学院网页设计JavaScript javascript处理事件的一些兼容写法 阅读

javascript处理事件的一些兼容写法

 2010-09-14 13:47:24 来源:WEB开发网   
核心提示:绑定事件varaddEvent=function(obj,type,fn){if(obj.addEventListener)obj.addEventListener(type,fn,false);elseif(obj.attachEvent){obj["e"+type+fn]=fn;obj.atta

绑定事件var addEvent = function( obj, type, fn ) { 
  if (obj.addEventListener) 
    obj.addEventListener( type, fn, false ); 
  else if (obj.attachEvent) { 
    obj["e"+type+fn] = fn; 
    obj.attachEvent( "on"+type, function() { 
      obj["e"+type+fn](); 
    } ); 
  } 
}; 

另一个实现var addEvent = (function () { 
  if (document.addEventListener) { 
    return function (el, type, fn) { 
      el.addEventListener(type, fn, false); 
    }; 
  } else { 
    return function (el, type, fn) { 
      el.attachEvent('on' + type, function () { 
        return fn.call(el, window.event); 
      }); 
    } 
  } 
})(); 

移除事件var removeEvent = function(obj, type, fn) { 
  if (obj.removeEventListener) 
    obj.removeEventListener( type, fn, false ); 
  else if (obj.detachEvent) { 
    obj.detachEvent( "on"+type, obj["e"+type+fn] ); 
    obj["e"+type+fn] = null; 
  } 
} 

加载事件与脚本var loadEvent = function(func) { 
  var oldonload = window.onload; 
  if (typeof window.onload != 'function') { 
    window.onload = func; 
  }else { 
    window.onload = function() { 
      oldonload(); 
      func(); 
    } 
  } 
} 

阻止事件var cancelEvent = function(event) { 
  event = event||window.event 
  if (event.preventDefault) { 
    event.preventDefault( ); 
    event.stopPropagation( ); 
  } else { 
    event.returnValue = false; 
    event.cancelBubble = true; 
  } 
} 

取得事件源对象

相当于Prototype.js框架的Event.element(e)

var getTarget = function(event){ 
  event = event || window.event; 
  var obj = event.srcElement ? event.srcElement : event.target; 
  return obj 
}

Tags:javascript 处理 事件

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接