如何实现JS主动触发事件

 1 function triggerMouseOver(selector) {
 2   const targetElement = document.querySelector(selector);
 3   if (document.createEvent) {
 4     const event = document.createEvent('MouseEvents');
 5     event.initEvent('mouseover', true, false);
 6     targetElement.dispatchEvent(event);
 7   } else if (document.createEventObject) {
 8     //兼容IE
 9     targetElement.fireEvent('onmouseover');
10   }
11 }
12 
13 function triggerFocus(selector) {
14   const targetElement = document.querySelector(selector);
15   if (document.createEvent) {
16     const event = document.createEvent('HTMLEvents');
17     event.initEvent('focus', true, false);
18     targetElement.dispatchEvent(event);
19   } else if (document.createEventObject) {
20     //兼容IE
21     targetElement.fireEvent('focus');
22   }
23 }

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后必须初始化才能触发

 1 // 通用 Events 和 HTMLEvents
 2 event.initEvent( 'type', bubbles, cancelable )
 3 // UIEvents
 4 event.initUIEvent( 'type', bubbles, cancelable, windowObject, detail )
 5 //MouseEvents
 6 event.initMouseEvent( 'type', bubbles, cancelable, windowObject, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget )
 7 //MutationEvents
 8 event.initMutationEvent( 'type', bubbles, cancelable, relatedNode, prevValue, newValue, attrName, attrChange ) 
 9 
10 // 在目标元素上触发事件, 需要注意的是在IE 5.5+版本上请用fireEvent方法
11 targetElement.dispatchEvent( event )

举个栗子(主动触发 mouseover 事件)

  1. 主动触发 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);
  1. 主动触发 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');
}

 

作者:mocobk
链接:https://www.jianshu.com/p/7b92cc91f9cd
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted on 2022-03-10 15:11  天军  阅读(3360)  评论(1编辑  收藏  举报

导航