原生dom事件注册和移除事件的封装

复制代码
var addEvent = (function() {
    var setListener;
    setListener = false;
    return function(el, ev, fn) {
      if (!setListener) {
        if (el.addEventListener) {
          setListener = function(el, ev, fn) {
            return el.addEventListener(ev, fn, false);
          };
        } else if (el.attachEvent) {
          setListener = function(el, ev, fn) {
            return el.attachEvent(ev, fn, false);
          };
        } else {
          setListener = function(el, ev, fn) {
            return el['on' + ev] = fn;
          };
        }
      }
      return setListener(el, ev, fn);
    };
  })();

  var fireEvent = function(element, event) {
    var evt;

    if (doc.createEventObject) {
      return element.fireEvent('on' + event, evt);
    } else {
      evt = document.createEvent('HTMLEvents');
      evt.initEvent(event, true, true);
      return !element.dispatchEvent(evt);
    }
  };
复制代码

 

posted @   飘然离去  阅读(458)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示