1. document.createEvent(eventType)
参数:eventType 共5种类型:
eventType | 包含事件 |
---|---|
Events | 包括所有的事件 |
HTMLEvents |
abort , blur , change , error , focus , load , reset , resize , scroll ,select , submit , unload
|
UIEevents |
DOMActivate , DOMFocusIn , DOMFocusOut , keydown , keypress , keyup
|
MouseEvents |
click , mousedown , mousemove , mouseout , mouseover , mouseup
|
MutationEvents |
DOMAttrModified , DOMNodeInserted , DOMNodeRemoved , DOMCharacterDataModified , DOMNodeInsertedIntoDocument , DOMNodeRemovedFromDocument , DOMSubtreeModified
|
document.createEvent后必须初始化才能触发
// 通用 Events 和 HTMLEvents
event.initEvent( 'type', bubbles, cancelable )
// UIEvents
event.initUIEvent( 'type', bubbles, cancelable, windowObject, detail )
//MouseEvents
event.initMouseEvent( 'type', bubbles, cancelable, windowObject, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget )
//MutationEvents
event.initMutationEvent( 'type', bubbles, cancelable, relatedNode, prevValue, newValue, attrName, attrChange )
// 在目标元素上触发事件, 需要注意的是在IE 5.5+版本上请用fireEvent方法
targetElement.dispatchEvent( event )
举个栗子(主动触发 mouseover 事件)
- 主动触发 click 事件
// 使用通用类型创建 click 事件
const event = document.createEvent('Events');
event.initEvent( 'click', true, false );
const targetElement = document.getElementById('someID');
targetElement.dispatchEvent(event);
// 使用通 MouseEvents 创建 click 事件
const event = document.createEvent('MouseEvents');
event.initMouseEvent( 'click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
const targetElement = document.getElementById('someID');
targetElement.dispatchEvent(event);
- 主动触发 mouseover 事件, 并考虑对 IE 的兼容
const targetElement = document.getElementById('someID');
if ( document.createEvent ) {
const event = document.createEvent('MouseEvents');
event.initEvent( 'mouseover', true, false );
targetElement.dispatchEvent(event);
}else if ( document.createEventObject ) {
//兼容IE
targetElement.fireEvent('onmouseover');
}
网友评论