JS的事件绑定

绑定事件

  1. onclick,无兼容性问题,但是多次绑定会互相覆盖
e.onclick = null; // 解绑时,设置为null即可 
  1. addEventListener,w3c的标准方式,如果绑定多次不会互相覆盖
e.removeEventListener(event.type, handle, boolean); // 解绑参数与绑定相同
  1. attachEvent,IE的独有方式,绑定多次不会互相覆盖,只在冒泡阶段触发
e.detachEvent(event.type, handle); // 解绑
兼容的事件绑定方法
function addEvent(ele, event, handle, bool) {
  if(ele.addEventListener) {
    ele.addEventListener(event, handle, bool);
  } else if(ele.attachEvent) {
    ele.attachEvent("on"+event, handle);
  } else {
    ele["on"+event] = handle;
  }
}
兼容的事件解绑方法
function removeEvent(ele, event, handle, bool) {
  if(ele.removeEventListener) {
    ele.removeEventListener(event, handle, bool);
  } else if(ele.detachEvent) {
    ele.detachEvent("on"+event, handle);
  } else {
    ele["on"+event] = null;
  }
}

阻止默认事件

  1. onclick => return false;
  2. addEventListener => event.preventDefault(); // event = e || window.event;
  3. attachEvent => event.returnValue = false;

阻止事件冒泡与捕获

  1. 标准:event.stopPropagation();
  2. IE:event.cancelBubble = true;

事件委托

先将事件绑定到父元素,然后再根据e.target或e.srcElement确定实际触发事件的子元素,而后进行相应的操作。

触发事件

var ele = document.body;
var event = document.createEvent("HTMLEvents");
event.initEvent("scroll", true, false);
ele.dispatchEvent(event);
  1. createEvent的参数包括五种:
    Events:包括所有事件
    UIEvents:包括DOMActivate, DOMFocusIn, DOMFocusOut, keydown, keypress, keyup 以及 所有MouseEvents
    HTMLEvents:包括abort, blur, change, error, focus, scroll, load, reset, select, submit, unload
    ** MouseEvents:包括click, mousedown, mousemove, mouseover, mouseout, mouseup
    ** MutationEvents:
    都不常用就不列举了
  2. 需要通过initEvent初始化
    HTMLEvents和Events:initEvent(type, bubbles, cancelable);
    ** UIEvents:initUIEvent(type, bubbles, cancelable, windowObject, detail);
    ** MouseEvents:
    initMouseEvent(type, bubbles, cancelable, windowObject, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget);
    ** MutationEvents:**initMutationEvent(type, bubbles, cancelable, relatedNode, prevValue, newValue, attrName, attrChange);
  3. 最后使用dispatchEvent来触发
  4. 若是IE浏览器,可以跳过前三步,直接使用el.fireEvent(type)来触发

你可能感兴趣的:(JS的事件绑定)