外观模式

// 统一外观
function addEvent (el, type, fn) {
  function handler(e) {
    e = e || window.event;
    e.target =e.target ||  e.srcElement;
    e.stopPropagation = e.stopPropagation || function() { e.cancelBubble = true };
    e.preventDefault = e.preventDefault || function() {window.event.returnValue = false; }
    fn.apply(this, arguments);
  }
  if (el.addEventListener) {
    el.addEventListener(type, handler, false);
  }
  else if (el.attachEvent) {
    el.attachEvent('on' + type, handler, false);
  }
  else {
    el['on' + type] = handler;
  }
}

function setStyle(el, opt) {
  for (var attr in opt) {
    if (opt.hasOwnProperty(attr)) {
      el.style[attr] = opt[attr];
    }
  }
}

//demo
addEvent(document.body, 'click', function(e) {
  e.preventDefault(); // 阻止默认事件
  setStyle(this, {border: '1px solid red'});
  console.log(e.target);
});

你可能感兴趣的:(外观模式)