事件操作的兼容性写法

  • Post author:
  • Post category:其他


    var commonEvent = {
      addEvent: function (ele, type, handler) {
        if (ele.addEventListener) {
          ele.addEventListener(type, handler, false);
        } else if (ele.attachEvent) {
          ele.attachEvent('on' + type, handler);
        } else {
          ele['on' + type] = handler;
        }
      },
      removeEvent: function (ele, type, handler) {
        if (ele.removeEventListener) {
          ele.removeEventListener(type, handler, false);
        } else if (ele.detachEvent) {
          ele.detachEvent('on' + type, handler);
        } else {
          ele['on' + type] = null;
        }
      },
      stopPropagation: function (e) {
        if (e.stopPropagation) {
          e.stopPropagation();
        } else {
          e.cancelBubble = true;
        }
      },
      preventDefault: function (e) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      },
      getEvent: function (e) {
        return e || window.event;
      },
      getTarget: function (e) {
        return e.target || e.srcElement;
      }
    }



版权声明:本文为Lxj1107020234原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。