On the _javascript techniques of JavaScript event simulation

Source: Internet
Author: User
Tags modifiers
This means that there will be an appropriate event bubbling, and the browser will execute the assigned event handler. This ability is useful when testing Web applications, providing a way to simulate specific events in the DOM 3 specification, IE9 Chrome FF Opera and safari support such a way that in IE8 and previous ways IE browsers have his own way to simulate events
A) Dom event simulation
You can create an event object at any time by using the CreateEvent () method on the document, which takes only one argument, creating an event string for the event object, all strings in the DOM2 level are plural, and the DOM All strings in the Level 3 event are singular, with all strings as follows:
Uievents: Common UI events, mouse event keyboard events are inherited from UI events, and Uievent is used at the DOM level 3.
Mouseevents: Common mouse events, using MouseEvent at the DOM level 3.
Mutationevents: Common mutation event, used at DOM 3 level is mutationevent.
Htmlevents: Common HTML events are not equivalent at the DOM3 level.
Note that IE9 is the only browser that supports DOM3-level keyboard events, but other browsers also provide other methods that can be used to simulate keyboard events.
Once an event object is created, the information about the event is initialized, each type of event has a specific method to initialize, and after the event object is created, the event is applied to a particular DOM node by the Dispatchevent () method so that it supports the event. This dispatchevent () event, which supports a parameter, is the event object you created.
(b) Mouse event simulation
Mouse events can be modeled by creating a mouse event object (mouse event) and giving him some relevant information, creating a mouse event to create a mouse event object by passing the CreateEvent () method A string "Mouseevents". The Inimouseevent () method is then used to initialize the returned event object, and the Inimouseevent () method accepts the 15 parameter as follows:
Type string: The type of event to trigger, such as ' click '.
Bubbles Boolean Type: Indicates whether the event should be bubbling, and the value should be set to true for mouse event impersonation.
cancelable BOOL Type: Indicates whether the event can be canceled, and the value should be set to true for mouse event impersonation.
View Abstract View: Event-Granted view, this value is almost entirely document.defaultview.
Detail int Type: Additional event information This initialization should normally default to 0.
ScreenX int Type: event distance to the X coordinate of the left side of the screen
ScreenY int Type: Event from the y-coordinate at the top of the screen
ClientX int Type: Event distance to the left of the visual region X coordinate
ClientY int Type: event distance to the y-coordinate of the top of the visible region
Ctrlkey Boolean type: Represents whether the Ctrol key is pressed, and the default is False.
Altkey Boolean type: Represents whether the ALT key is pressed, and the default is False.
Shiftkey Boolean type: Represents whether the SHIF key is pressed, and the default is False.
Metakey Boolean type: Represents whether the meta key is pressed and false by default.
button int type: Represents the mouse button being pressed, which defaults to 0.
Relatedtarget (object): The associated object of the event. Only used when simulating mouseover and mouseout.

Notably, the Initmouseevent () parameter is directly matched to the event object, where the first four parameters are used by the browser, and only the event handler uses other parameters, and when the event object is passed as a parameter to the dispatch () method, The target property is automatically assigned a value. Here is an example of
Copy Code code as follows:

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 a DOM-implemented browser, all other events include Dbclick, which can be implemented in the same way.
c) Keyboard Event simulation
It is noteworthy that the keyboard event has been removed from the DOM2 level event, and that at first the keyboard event was part of the draft in the DOM2-level event, but the final version was removed and FF has implemented the keyboard event in the draft version, It is noteworthy that the keyboard events implemented in the DOM3 level event are significantly different from the keyboard events in the DOM2-level event draft version.
Creating a keyboard event object in a DOM3 event is done using the CreateEvent () method and passing in the KeyboardEvent string as a parameter, invoking the Initkeyboadevent () method initialization on the returned event object, There are several parameters for initializing keyboard events:
Type (string)-types of events to be triggered, such as "KeyDown".
Bubbles (Boolean)-represents whether the event should be bubbling.
Cancelable (Boolean)-Represents whether an event can be canceled.
View (Abstractview)-is the graph of the event being granted. The usual values are: Document.defaultview.
Key (String)-the code that corresponds to the key that is pressed.
Location (integer)-the position where the key is pressed. 0: Default keyboard, 1 left position, 2 right position, 3 digit keypad area, 4 virtual keyboard area, or 5 game handle.
Modifiers (string)-a list of modifiers that are separated by spaces.
Repeat (integer)-the number of times a key in a row is pressed.
Note that in the DOM3 event, the KeyPress event is wasted, so you can only simulate the KeyDown and KeyUp events on the keyboard in the following way.
Copy Code code as follows:

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 a keyboard event by using Document.createevent (' keyevents '), which is the method of initializing the Initkeyevent (), which accepts 10 parameters,
Type (string)-types of events to be triggered, such as "KeyDown".
Bubbles (Boolean)-represents whether the event should be bubbling.
Cancelable (Boolean)-Represents whether an event can be canceled.
View (Abstractview)-is the graph of the event being granted. The usual values are: Document.defaultview.
Ctrlkey (Boolean)-Represents whether the Ctrol key is pressed. Default false.
Altkey (Boolean)-Represents whether the ALT 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)-keys are pressed or released when the key is corresponding to the key code. The default is 0;
CharCode (integer)-the ASCII code corresponding to the character of the pressed key. Is the default for a total KeyPress event is 0.
D) Simulate other events
Mouse events and keyboard events are the longest-simulated events in the browser, but at some point they also need to simulate mutation events and HTML events. You can use CreateEvent (' mutationevents ') to create a mutation event object that can initialize this event object with Initmutationevent (), including type, Bubbles, cancelable, Relatednode, Prevvalue,
NewValue, Attrname, and Attrchange. The following method can be used to simulate a mutation event:
var event = document.createevent (' mutationevents ');
Event.initmutationevent ("domnodeinserted", True, False, Somenode, "", "", ",", 0);
Target.dispatchevent (event);
For HTML events, go directly to the code.
var event = document.createevent ("htmlevents");
Event.initevent ("Focus", true, false);
Target.dispatchevent (event);
For mutation events and HTML events are rarely used in browsers because they accept application restrictions.
E) customizing DOM events
A class of events defined in the DOM3 level event called custom event, which I call the customer incident, is not native to the DOM, but is provided directly so that developers can create their own events, you can create a customer event of your own, by calling CreateEvent (' customevent '), the returned event object is invoked, the Initcustomevent () method, which passes four parameter type,bubbles,cancelable,detail. PS: Little brother on this part of the understanding is limited, here is just a draw.
F) event simulation in IE
From IE8, as well as earlier versions of IE, are mimicking the way DOM simulates events: Creating event objects, initializing event information, and triggering events. Of course, ie in the process of completing these several steps is different.
First, unlike the method of creating an Event object in the DOM, IE uses the Document.createeventobject () method with no parameters, returns a generic event object, and assigns a value to the returned event object, at which point IE does not provide initialization functions, You can only use a physical method one assignment, and finally call the FireEvent () method on the target element, with a parameter of two: the name of the event handler and the event object created. When the FireEvent method is invoked, the Srcelement and type properties of the event object are automatically assigned, and others will need to be assigned manually. Take a look at the following example:
Copy Code code as follows:

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);

This example creates an event object, and then initializes the event object with some information, noting that the assignment of the event property is unordered, and that these property values are not important for event objects, because only the handler functions corresponding to the event handle (an event handler) use them. There is no difference between event objects that create mouse events, keyboard events, or other events, because a common event object can be triggered by any type of event.
It is noteworthy that in the DOM keyboard event simulation, the result of a keypress mock event will not appear as a character in the textbox, even if the corresponding event handler function has been triggered.
Compared with the DOM event simulation, the individual feels that the event simulation of IE is more easy to remember and accept, the unified event model can bring some convenience.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.