Document.createEvent()

警告: createEvent 使用的许多方法,如 initCustomEvent,都被废弃了。请使用 event constructors 来替代。

创建一个指定类型的事件。其返回的对象必须先初始化并可以被传递给 element.dispatchEvent (en-US)

语法

var event = document.createEvent(type);
  • event 就是被创建的 Event 对象。
  • type 是一个字符串,表示要创建的事件类型。事件类型可能包括"UIEvents""MouseEvents""MutationEvents" 或者 "HTMLEvents"。请查看注意小节获取详细信息。

示例

// 创建事件
var event = document.createEvent('Event');

// 定义事件名为'build'.
event.initEvent('build', true, true);

// 监听事件
elem.addEventListener('build', function (e) {
  // e.target matches elem
}, false);

// 触发对象可以是任何元素或其他事件目标
elem.dispatchEvent(event);

参考

注意

Event type 字符串只能传递事件模块中定义的值给 CreateEvent。其中一些事件模块是在 DOM 事件规范定义的,还有些事在其他规范定义的(如 SVG),还有一些是 Gecko-specific 事件。详情见下表。

To-do: 添加事件名称到下表中。

事件模块 传递给 createEvent 的 Event type 事件初始化方法
DOM Level 2 Events
User Interface event module "UIEvents" event.initUIEvent (en-US)
Mouse event module "MouseEvents" event.initMouseEvent (en-US)
Mutation event module "MutationEvents" event.initMutationEvent
HTML event module "HTMLEvents" event.initEvent (en-US)
DOM Level 3 Events
User Interface event module "UIEvent", "UIEvents" event.initUIEvent (en-US)
Mouse event module "MouseEvent", "MouseEvents" event.initMouseEvent (en-US)
Mutation event module "MutationEvent", "MutationEvents" event.initMutationEvent
Mutation name event module (not implemented in Gecko as of June 2006) "MutationNameEvent" event.initMutationNameEvent
Text event module "TextEvent" (Gecko also supports "TextEvents") event.initTextEvent (not implemented)
Keyboard event module "KeyboardEvent" (Gecko also supports "KeyEvents") event.initKeyEvent (Gecko-specific; the DOM 3 Events working draft uses initKeyboardEvent instead)
Custom event module "CustomEvent" event.initCustomEvent (en-US)
Basic events module "Event" (Gecko also supports "Events") event.initEvent (en-US)
SVG 1.1 Scripting
SVG "SVGEvents" (Gecko also supports "SVGEvent") event.initEvent (en-US)
"SVGZoomEvents" (Gecko also supports "SVGZoomEvent") event.initUIEvent (en-US)
Other event types supported by Gecko
- "MessageEvent" event.initMessageEvent
"MouseScrollEvents", "PopupEvents" event.initMouseEvent (en-US)
"PopupBlockedEvents" event.initPopupBlockedEvent
"XULCommandEvent", "XULCommandEvents" event.initCommandEvent
Progress Events "ProgressEvent" ProgressEvent.initProgressEvent() (en-US)已弃用 非标准
Animation Events "AnimationEvent" (or "WebKitAnimationEvent" for WebKit/Blink-based browsers) AnimationEvent.initAnimationEvent() (en-US)已弃用 非标准
Transition Events "TransitionEvent" (or "WebKitTransitionEvent" for WebKit/Blink-based browsers) TransitionEvent.initTransitionEvent() (en-US)已弃用 非标准

有些事件可以使用两种事件类型参数,这是因为 DOM Level 3 Events 将事件类型参数更改为单数形式,但是仍然支持老的复数形式以向后兼容。

规范