已废弃
该特性已经从 Web 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性。
Mutation 事件 为web页面提供一种机制或扩展,以便在DOM被改变时获得通知。如果可能请用Mutation Observers代替。
序言
这个 mutation 事件在DOM Events 标准 中已被列为反对使用 , 因为在API的设计中有缺陷 (详情见 "DOM Mutation Events Replacement: The Story So Far / Existing Points of Consensus" 发表于 public-webapps).
Mutation Observers 在DOM4中被提议用来取代mutation事件. 预计它们被列入 in Firefox 14 and Chrome 18中。
避免用mutation事件的实际原因是性能问题和跨浏览器支持。
性能
Adding DOM mutation listeners to a document profoundly degrades the performance of further DOM modifications to that document (making them 1.5 - 7 times slower!). Moreover, removing the listeners does not reverse the damage.
The performance effect is limited to the documents that have the mutation event listeners.
跨浏览器支持
These events are not implemented consistently across different browsers, for example:
- IE prior to version 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for example, DOMNodeInserted)
- WebKit doesn't support DOMAttrModified (see webkit bug 8191 and the workaround)
- "mutation name events", i.e. DOMElementNameChanged and DOMAttributeNameChanged are not supported in Firefox (as of version 11), and probably in other browsers as well.
- ...
Dottoro documents browser support for mutation events.
Mutation 事件列表
The following is a list of all mutation events, as defined in DOM Level 3 Events specification:
DOMAttrModified
DOMAttributeNameChanged
DOMCharacterDataModified
DOMElementNameChanged
DOMNodeInserted
DOMNodeInsertedIntoDocument
DOMNodeRemoved
DOMNodeRemovedFromDocument
DOMSubtreeModified
使用
You can register a listener for mutation events using element.addEventListener as follows:
element.addEventListener("DOMNodeInserted", function (ev) {
// ...}, false);
The event object is passed to the listener in a MutationEvent
(see its definition in the specification) for most events, and MutationNameEvent
for DOMAttributeNameChanged
and DOMElementNameChanged
.