js手動觸發事件

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <title>js手動觸發事件</title>
  <script>  	
	
    window.onload = function(){
		var oA = document.getElementById('clickme');
		var DownloadEvt = null;
		if (document.createEvent) {
			if (DownloadEvt === null){
				DownloadEvt = document.createEvent('MouseEvents');
			}
			DownloadEvt.initEvent('click', true, false);
			oA.dispatchEvent(DownloadEvt);
		} else if (document.createEventObject) {
			oA.fireEvent('onclick');
		} else if (typeof oA.onclick == 'function') {
			oA.onclick();
		}
		
	}
  </script>
</head>

<body>
  <a id='clickme' href='https://blog.csdn.net/qq_36412715/article/details/104636155'></a>
</body>

</html>

JS手動觸發事件用到的方法:

1. createEvent(eventType)

參數:eventType 共5種類型:

Events :包括所有的事件. 
      HTMLEvents:包括 'abort', 'blur', 'change', 'error', 'focus', 'load', 'reset', 'resize', 'scroll', 'select', 
                                'submit', 'unload'. 事件
      UIEvents :包括 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'keydown', 'keypress', 'keyup'.
                              間接包含 MouseEvents. 
      MouseEvents:包括 'click', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup'. 
      MutationEvents:包括 'DOMAttrModified', 'DOMNodeInserted', 'DOMNodeRemoved', 
                                  'DOMCharacterDataModified', 'DOMNodeInsertedIntoDocument', 
                                  'DOMNodeRemovedFromDocument', 'DOMSubtreeModified'. 

2. 在createEvent後必須初始化

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(event)

dom.dispatchEvent(eventObject), 參數eventObject表示事件對象,是createEvent()方法返回的創建的Event對象。

需要注意的是在IE 8以下版本請用fireEvent方法。

參考:https://www.cnblogs.com/jiangxiaobo/p/5830200.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章