一般的相容做法,如下: 跨瀏覽器添加事件 跨瀏覽器移除事件 推薦寫法 參考地址: addEvent() recoding contest entry addEvent() – Follow Up ...
一般的相容做法,如下:
跨瀏覽器添加事件
//跨瀏覽器添加事件 function addEvent(obj,type,fn){ if(obj.addEventListener){ obj.addEventListener(type,fn,false); }else if(obj.attachEvent){//IE obj.attchEvent('on'+type,fn); } }
跨瀏覽器移除事件
//跨瀏覽器移除事件 function removeEvent(obj,type,fn){ if(obj.removeEventListener){ obj.removeEventListener(type,fn,false); }else if(obj.detachEvent){//相容IE obj.detachEvent('on'+type,fn); } }
推薦寫法
function addEvent( obj, type, fn ) { if ( obj.attachEvent ) { obj['e'+type+fn] = fn; obj[type+fn] = function(){obj['e'+type+fn]( window.event );} obj.attachEvent( 'on'+type, obj[type+fn] ); } else obj.addEventListener( type, fn, false ); } function removeEvent( obj, type, fn ) { if ( obj.detachEvent ) { obj.detachEvent( 'on'+type, obj[type+fn] ); obj[type+fn] = null; } else obj.removeEventListener( type, fn, false ); }
參考地址:
addEvent()
recoding contest entry