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


    绑定事件

    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
  • 相关阅读:
    ssh 远程命令
    POJ 2287
    POJ 2376
    hihoCoder1488
    POJ1854
    HDU 5510
    HDU 4352
    CodeForces 55D
    HDU 1517
    CodeForces 1200F
  • 原文地址:https://www.cnblogs.com/luluping/p/1530600.html
Copyright © 2020-2023  润新知