Events are used to describe a specific interesting moment in a web page. As we all know, events are usually triggered when the user interacts with the browser. In fact, this is not the case. Specific events can be triggered at any time through Javascript, and these events are related to The events created by the browser are the same. This means that the appropriate events will bubble up and the browser will execute the assigned event handlers. This ability is very useful when testing web applications. The DOM level 3 specification provides methods to simulate specific events. IE9 chrome FF Opera and Safari support this method. In IE8 and previous methods, Internet Explorer has its own way of simulating events.
Javascript event simulation
a)Dom event simulation
You can create an event object at any time through the createEvent() method on the document. This method only accepts one parameter, which is the event string of the event object to be created. In the DOM2 level specification, all strings are in plural form. In the DOM All strings on level 3 events are in singular form. All strings are as follows:
UIEvents: Universal UI events. Mouse events and keyboard events are all inherited from UI events. UIEvent is used on DOM level 3.
MouseEvents: General mouse events, MouseEvent is used at DOM level 3.
MutationEvents: Universal mutation event, MutationEvent is used at DOM level 3.
HTMLEvents: Universal HTML events, there is no equivalent at DOM3 level.
Note that ie9 is the only browser that supports DOM3 level keyboard events, but other browsers also provide other available methods to simulate keyboard events.
Once an event object is created, the relevant information of the event must be initialized. Each type of event has a specific method to initialize. After the event object is created, the event is applied to the event through the dispatchEvent() method. On a specific dom node so that it supports this event. This dispatchEvent() event supports one parameter, which is the event object you created.
Related recommendations: "JavaScript Basic Tutorial"
b) Mouse event simulation
Mouse events can be simulated by creating a mouse event object (mouse event object), and grant him some relevant information, create a mouse event by passing a string "MouseEvents" to the createEvent() method to create a mouse event object, and then initialize the returned event object through the iniMouseEvent() method, iniMouseEvent( ) method accepts 15 parameters, the parameters are as follows:
type string type: the type of event to be triggered, such as 'click'.
Bubbles Boolean type: Indicates whether the event should bubble. For mouse event simulation, this value should be set to true.
Cancelable bool type: Indicates whether the event can be canceled. For mouse event simulation, this value should be set to true.
view abstract view: the view granted by the event, this value is almost always document.defaultView.
detail int type: additional event information, this should generally default to 0 during initialization.
ScreenX int type: X coordinate from the event to the left side of the screen
ScreenY int type: Y coordinate from the top of the screen from the event
ClientX int type: X coordinate from the left side of the visible area from the event
clientY int type : The y coordinate of the event distance above the visible area
ctrlKey Boolean type: Represents whether the ctrol key is pressed, the default is false.
altKey Boolean type: Represents whether the alt key is pressed, the default is false.
shiftKey Boolean type: represents whether the shift key is pressed, the default is false.
metaKey Boolean type: Represents whether the meta key is pressed. The default is false.
Button int type: Represents the pressed mouse button, the default is zero.
relatedTarget (object): The related object of the event. Only used when simulating mouseover and mouseout.
It is worth noting that the parameters of initMouseEvent() are directly mapped to the event object. The first four parameters are used by the browser. Only the event processing function uses other parameters. When the event object is passed as a parameter For the dispatch() method, the target attribute will be automatically assigned a value. Below is an example,
var btn = document.getElementById(“myBtn”); var event = document.createEvent(“MouseEvents”); event.initMouseEvent(“click”, true, true, document.defaultView, 0, 0, 0, 0, 0,false, false, false, false, 0, null); btn.dispatchEvent(event);
In DOM-implemented browsers, all other events, including dbclick, can be implemented in the same way.
c) Keyboard event simulation
It is worth noting that keyboard events have been moved out of DOM2-level events. Initially, in the draft version of DOM2-level events, keyboard events were included as part of the draft. , but was removed in the final version, FF has implemented the keyboard events in the draft version. It is worth noting that the keyboard events implemented in DOM3 level events are still very different from the keyboard events in the DOM2 level event draft version.
Creating a keyboard event object in a dom3 level event is through the createEvent() method and passing in the KeyBoardEvent string as a parameter. For the returned event object, call the initKeyBoadEvent() method to initialize it. The parameters for initializing the keyboard event are as follows: Each:
Type (string) - The type of event to be triggered, such as "keydown".
Bubbles (Boolean) - Represents whether the event should bubble.
Cancelable (Boolean) - Represents whether the event can be canceled .
view (AbstractView) — The view that was granted the event. Usually the value is: document.defaultView.
key (string) — The code corresponding to the pressed key.
Location (integer) — The pressed key The location. 0: Default keyboard, 1 left position, 2 right position, 3 numeric keyboard area, 4 virtual keyboard area, or 5 game controller.
modifiers (string) — A space-separated list of modifiers .
repeat (integer) — The number of times a key is pressed in a row.
Please note that in the DOM3 event, the keypress event is wasted, so in the following way, you can only simulate the keyboard keydown and keyup events on.
var textbox = document.getElementById(“myTextbox”),event; if (document.implementation.hasFeature(“KeyboardEvents”, “3.0”)){ event = document.createEvent(“KeyboardEvent”); event.initKeyboardEvent(“keydown”, true, true, document.defaultView, “a”,0, “Shift”, 0); } textbox.dispatchEvent(event);
Under FF, you are allowed to create keyboard events by using document.createEvent('KeyEvents'). The initialization method is initKeyEvent(). This method accepts 10 parameters.
Type (string) — The type of event to be triggered, such as "keydown".
Bubbles (Boolean) — Represents whether the event should bubble.
Cancelable (Boolean) — Represents whether the event can be canceled.
view (AbstractView) — The event is granted to the image. The usual value is: document.defaultView.
ctrlKey (Boolean) — Represents whether the ctrol key is pressed. Default is false.
altKey (Boolean) — Represents alt Whether the key is pressed. Default false.
shiftKey (Boolean) — Represents whether the shift key is pressed. Default false.
metaKey (Boolean) — Represents whether the meta key is pressed. Default false.
keyCode (integer ) — The key code corresponding to the key when the key is pressed or released. The default is 0;
charCode (integer) — The ASCII code corresponding to the character of the pressed key. The default used by the keypress event is 0.
D) Simulate other events
Mouse events and keyboard events are the most commonly simulated events in browsers, but sometimes mutation events and HTML events also need to be simulated. You can use createEvent('MutationEvents') to create a mutation event object. You can use initMutationEvent() to initialize the event object. The parameters include type, bubbles, cancelable, relatedNode, prevValue,
newValue, attrName, and attrChange. Yes Use the following method to simulate a mutation event:
var event = document.createEvent('MutationEvents'); event.initMutationEvent(“DOMNodeInserted”, true, false, someNode, “”,””,””,0); target.dispatchEvent(event);
For HTML events, enter the code directly.
var event = document.createEvent(“HTMLEvents”); event.initEvent(“focus”, true, false); target.dispatchEvent(event);
Mutation events and HTML events are rarely used in browsers because they are subject to application limitations.
E) Customized DOM events
In the DOM3 level event, a type of event is defined called custom event. I call it a customer event. Customer events will not be triggered by the DOM natively, but will be provided directly. As for developers who can create their own events, you can create your own customer event by calling createEvent('CustomEvent'), calling the initCustomEvent() method on the returned event object, passing four parameters: type, bubbles, cancelable , detail. ps: My understanding of this part is limited, so I am just giving some advice here.
F) Event simulation in IE
From IE8, and earlier versions of IE, they all imitate the way DOM simulates events: creating event objects, initializing event information, and then triggering events. Of course, IE's process of completing these steps is different.
First of all, different from the method of creating event objects in dom, IE uses the document.createEventObject() method and has no parameters. It returns a general event object. Next, it is necessary to assign a value to the returned event object. At this time, IE does not provide For the initialization function, you can only use physical methods to assign values one by one, and finally call the fireEvent() method on the target element with two parameters: the name of the event handler and the created event object. When the fireEvent method is called, the srcElement and type attributes of the event object will be automatically assigned, and the others will need to be assigned manually. Please see the following example:
var btn = document.getElementById(“myBtn”); var event = document.createEventObject(); event.screenX = 100; event.screenY = 0; event.clientX = 0; event.clientY = 0; event.ctrlKey = false; event.altKey = false; event.shiftKey = false; event.button = 0; btn.fireEvent(“onclick”, event);
这个例子创建了一个事件对象,之后通过一些信息初始化该事件对象,注意事件属性的赋值是无序的,对于事件对象来说这些属性值不是很重要,因为只有事件句柄对应的处理函数(event handler)会用到他们。对于创建鼠标事件、键盘事件还是其他事件的事件对象之间是没有区别的,因为一个通用的事件对象,可以被任何类型的事件触发。
值得注意的是,在Dom的键盘事件模拟中,对于一个keypress模拟事件的结果不会作为字符出现在textbox中,即使对应的事件处理函数已经触发。
与DOM事件模拟相比,个人觉得IE的事件模拟更容易让人记忆和接受,统一的事件模型可以带来一些便捷。
The above is the detailed content of A brief discussion on Javascript event simulation. For more information, please follow other related articles on the PHP Chinese website!