博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2009-07-24 22:56  linFen  阅读(284)  评论(0编辑  收藏  举报

绑定事件

01.var addEvent = function( obj, type, fn ) {
02.    if (obj.addEventListener)
03.        obj.addEventListener( type, fn, false );
04.    else if (obj.attachEvent) {
05.        obj["e"+type+fn] = fn;
06.        obj.attachEvent( "on"+type, function() {
07.            obj["e"+type+fn]();
08.        } );
09.    }
10.};

另一个实现

01.var addEvent = (function () { 
02.    if (document.addEventListener) { 
03.        return function (el, type, fn) { 
04.            el.addEventListener(type, fn, false); 
05.        }; 
06.    } else
07.        return function (el, type, fn) { 
08.            el.attachEvent('on' + type, function () { 
09.                return fn.call(el, window.event); 
10.            }); 
11.        
12.    
13.})();

移除事件

1.var removeEvent = function(obj, type, fn) {
2.    if (obj.removeEventListener)
3.        obj.removeEventListener( type, fn, false );
4.    else if (obj.detachEvent) {
5.        obj.detachEvent( "on"+type, obj["e"+type+fn] );
6.        obj["e"+type+fn] = null;
7.    }
8.}

加载事件与脚本

01.var loadEvent = function(func) {
02.    var oldonload = window.onload;
03.    if (typeof window.onload != 'function') {
04.        window.onload = func;
05.    }else {
06.        window.onload = function() {
07.            oldonload();
08.            func();
09.        }
10.    }
11.}

阻止事件

01.var cancelEvent = function(event) {
02.    event = event||window.event
03.    if (event.preventDefault) {
04.        event.preventDefault(  );
05.        event.stopPropagation(  );
06.    } else {
07.        event.returnValue = false;
08.        event.cancelBubble = true;
09.    }
10.}

取得事件源对象

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

1.var getTarget = function(event){
2.    event = event || window.event;
3.    var obj = event.srcElement ? event.srcElement : event.target;
4.    return obj