綁定事件
- onclick,無兼容性問題荧呐,但是多次綁定會互相覆蓋
e.onclick = null; // 解綁時纷捞,設(shè)置為null即可
- addEventListener,w3c的標(biāo)準(zhǔn)方式武氓,如果綁定多次不會互相覆蓋
e.removeEventListener(event.type, handle, boolean); // 解綁參數(shù)與綁定相同
- attachEvent梯皿,IE的獨有方式,綁定多次不會互相覆蓋县恕,只在冒泡階段觸發(fā)
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;
}
}
阻止默認(rèn)事件
- onclick => return false;
- addEventListener => event.preventDefault(); // event = e || window.event;
- attachEvent => event.returnValue = false;
阻止事件冒泡與捕獲
- 標(biāo)準(zhǔn):event.stopPropagation();
- IE:event.cancelBubble = true;
事件委托
先將事件綁定到父元素东羹,然后再根據(jù)e.target或e.srcElement確定實際觸發(fā)事件的子元素,而后進行相應(yīng)的操作忠烛。
觸發(fā)事件
var ele = document.body;
var event = document.createEvent("HTMLEvents");
event.initEvent("scroll", true, false);
ele.dispatchEvent(event);
- createEvent的參數(shù)包括五種:
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:都不常用就不列舉了 - 需要通過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); - 最后使用dispatchEvent來觸發(fā)
- 若是IE瀏覽器属提,可以跳過前三步,直接使用el.fireEvent(type)來觸發(fā)