Document:createEvent() 方法
警告:
与 createEvent
一起使用的许多方法(例如 initCustomEvent
)已被弃用。请使用 event 构造函数代替。
创建指定类型的事件。应首先初始化返回的对象,然后将其传递给 EventTarget.dispatchEvent
。
语法
js
createEvent(type)
参数
返回值
Event 对象。
示例
js
// 创建事件
const event = document.createEvent("Event");
// 定义事件名称为 'build'。
event.initEvent("build", true, true);
// 监听事件。
elem.addEventListener(
"build",
(e) => {
// e.target 与元素匹配
},
false,
);
// 目标可以是任何元素或其他 EventTarget。
elem.dispatchEvent(event);
备注
适合传递给 createEvent()
的事件类型字符串列于 DOM 标准——参见步骤 2 中的表格。请记住,大多数事件对象现在都有构造函数,这是创建事件对象实例的现代推荐方法。
规范
Specification |
---|
DOM # dom-document-createevent |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
createEvent |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- Deprecated. Not for use in new websites.
- See implementation notes.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.