使用js觸發事件
如果大家將一張網頁看成一個form的話,大致上就成了一個web form的模型。在win form 下要想手動觸發某一個物件的事件是很簡單的,只要傳送一條訊息即可達成。(PostMessage) 但是網頁並不是基於訊息機制的,如果我們想在一張網頁上寫出一個類似於按鍵精靈的功能該如何實現呢?
為大家介紹js下的幾個方法:
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.MutationEvents:包括 ‘DOMAttrModified’, ‘DOMNodeInserted’, ‘DOMNodeRemoved’,
‘DOMCharacterDataModified’, ‘DOMNodeInsertedIntoDocument’,
‘DOMNodeRemovedFromDocument’, ‘DOMSubtreeModified’.在createEvent後必須初始化,為大家介紹5種對應的初始化方法
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 )在初始化完成後就可以隨時觸發需要的事件了,為大家介紹targetObj.dispatchEvent(event)
使targetObj物件的event事件觸發
需要注意的是在IE 5.5+版本上請用fireEvent方法,還是瀏覽相容的考慮例子
//例子1 立即觸發滑鼠被按下事件
var fireOnThis = document.getElementByIdx_x('someID');
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent( 'click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
fireOnThis.dispatchEvent(evObj);
//例子2 考慮相容性的一個滑鼠移動事件
var fireOnThis = document.getElementByIdx_x('someID');
if( document.createEvent )
{
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'mousemove', true, false );
fireOnThis.dispatchEvent(evObj);
}
else if( document.createEventObject )
{
fireOnThis.fireEvent('onmousemove');
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0">
<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
<title></title>
</head>
<body>
<div id="a" onclick="alert(1);">321321</div>
<script type="text/javascript">
// 立即觸發滑鼠按下事件
var fireOnThis = document.getElementById('a');
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click',true,true,window,1,12,345,7,220,false,false,true,false,0,null);
fireOnThis.dispatchEvent(evObj);
</script>
</body>
</html>