[JavaScript]- createEvent() to create custom events

document.createEvent is used to create events. There are HTMLEvents, MouseEvents, and UIEvents  event types in DOM Level 2 events. DOM Level 3 adds many event types.

grammar:

createEvent(eventType)

parameter describe
eventType The event module name of the Event object you want to get.

See the " Description" section for a list of valid event types.

return value

Returns a newly created  Event  object, of the specified type.

illustrate

This method will create a new event type specified by the parameter  eventType  . Note that the value of this parameter is not the name of the event interface to create, but the name of the DOM module that defines that interface.

The following table lists the   legal values ​​for eventType and the event interface created by each value:

parameter event interface initialization method
HTMLEvents HTMLEvent iniEvent()
MouseEvents MouseEvent iniMouseEvent()
UIEvents UIevent iniUIEvent()

After creating an Event object using this method, the object must be initialized using the initialization methods shown in the table above. See the Event  Object Reference for details on initialization methods  .

This method is not actually defined by the Document interface, but by the DocumentEvent interface. If an implementation supports the Event module, then the Document object implements the DocumentEvent interface and supports this method.

The steps to create a custom event for a DOM element are:

1. Create an event: let event = document.createEvent('HTMLEvents');

Second, the initialization event:

          // initEvent accepts 3 parameters:

          // Event type, whether to bubble, whether to prevent the default behavior of the browser

          event.initEvent("mouseenter", true, true);

3. Add event listener to DOM: lis[index].addEventListener('custom event name', function(){})

4. Distribute (trigger) custom events:

          //Trigger events on DOM elements bound to event handles, such as mouseenter, mouseleave events, etc.

          lis[index].dispatchEvent(event);

 let event = document.createEvent('HTMLEvents');

event.initEvent("mouseenter", true, true);
     // initEvent接受3个参数:
     // 事件类型,是否冒泡,是否阻止浏览器的默认行为

lis[index].dispatchEvent(event);
     //触发lis[index]上绑定的mouseenter事件

Guess you like

Origin blog.csdn.net/m0_55960697/article/details/124144063
Recommended