DOM突变事件替换

Fra*_*ger 21 events html5 dom dom3 mutation-events

由于w3c将DOM变异标记为已弃用(请参阅http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents),是否有(快速)替代方法来检测属性修改在DOM?

ama*_*ma2 31

突变事件被弃用的原因是由于巨大的性能问题.

替换是Mutation Observers,请查看http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observershttps://developer.mozilla.org/en/DOM/DOM_Mutation_Observers

有关突变的信息作为MutationRecords的有序序列传递给观察者,表示已发生的观察到的变化序列

样品用法:

    var observer = new MutationObserver(function(mutationRecords) {
    // Handle mutations
     });

    observer.observe(myNode,
     {  // options:
     subtree: true,  // observe the subtree rooted at myNode
     childList: true,  // include information childNode insertion/removals
     attribute: true  // include information about changes to attributes within the subtree
    });
Run Code Online (Sandbox Code Playgroud)

Chrome 18和Firefox以及Webkit每晚构建都支持此功能.Firefox 14也将支持此功能.


And*_*rio 13

弃用的DOM*事件的一个很好的替代是animationStartCSS动画.大卫沃尔什写了这个方法.

首先,设置关键帧并将其应用于您想要监听的元素(不要忘记供应商前缀!):

@keyframes nodeInserted {  
  from { clip: rect(1px, auto, auto, auto); }
  to { clip: rect(0px, auto, auto, auto); }  
}

#parentElement > li {
  animation-duration: 0.001s;
  animation-name: nodeInserted;
}
Run Code Online (Sandbox Code Playgroud)

接下来,添加监听器:

var insertListener = function(event){
  if (event.animationName == "nodeInserted") {
    // This is the debug for knowing our listener worked!
    // event.target is the new node!
    console.warn("Another node has been inserted! ", event, event.target);
  }
}
document.addEventListener("animationstart", insertListener, false); // standard + firefox
document.addEventListener("MSAnimationStart", insertListener, false); // IE
document.addEventListener("webkitAnimationStart", insertListener, false); // Chrome + Safari
Run Code Online (Sandbox Code Playgroud)

当当!这是David的演示.Chrome浏览器的扩展程序可以将Google图片添加到Google Voice(请参阅content.css和inject.js).


Pet*_*ček 12

一年之后,有Mutation Observers来自DOM Level 4 的新的和闪亮的(按照那里的链接,他们解释了很多!).如果Mutation Event发射了一千次,MutationObserver只发射一次并包含所有修改并且可以访问.

适用于(截至2017/03):

  • Firefox 14+
  • IE 11
  • 边缘
  • Opera 15+
  • Chrome 26+(18至25前缀window.WebKitMutationObserver)
  • Safari 6.0(前缀window.WebKitMutationObserver)


Ren*_*nck 7

据我所知,没有其他选择(但是),因此DOMAttrModified只有在Firefox和Opera中才支持.在IE中你有这个onpropertychanged事件但是没有办法在Chrome/Safari中获得类似的功能.根据您要完成的工作以及您要定位的浏览器,您可以执行许多操作:

  • 将getter和setter定义为要监视的属性
  • 覆盖等的方法document.createAttribute,attributes.setNamedItem...

我自己一直在研究跨浏览器解决方案,但没有取得多大成功.你应该远离变异事件,因为它们不是跨浏览器而且非常慢.他们被弃用的原因很充分.如果您想了解更多,请阅读: