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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值