JavaScript-跨浏览器事件处理程序(EventUtil)

JavaScript-跨浏览器事件处理程序(EventUtil)

事件操作对象:

var EventUtil= {

  //添加事件

  addHandler: function (element, type, handler) {
    if (element.addEventListener) {
      element.addEventListener(type, handler, false);
    }else if (element.attachEvent) {  //IE
      element.attachEvent("on" + type, handler, false);
    } else {
      element["on" + type] = handler;
    }
  },

  //移除对象
  removeHandler: function (element, type, handler) {
    if (element.removeEventListener) {
      element.removeEventListener(type, handler, false);
    } else if (element.detachEvent) {  //IE
      element.detachEvent("on" + type, handler, false);
    } else {
      element["on" + type] = null;
    }
   },

  //获取事件对象
  getEvent: function (event) {
    return event ? event : window.event;
  },

  //获取目标对象
  getTarget: function (event) {
    return event.target || event.srcElement;
  },

  //取消默认事件
  preventDefault: function (event) {
    if (event.preventDefault) {
      event.preventDefault();
    } else {  
      event.returnValue;
    }
  },

  //停止冒泡

  stopPropagation: function (event) {
    if (event.stopPropagation) {
      event.stopPropagation();
    } else {

      event.cancelBubble = true;
    }
  }
};