2011-03-24 48 views

回答

7

据我所知,目前还没有其他选择,因此您只能在Firefox和Opera中支持DOMAttrModified。在IE中,您有onpropertychanged事件,但在Chrome/Safari中无法获得类似的功能。有一些事情你可以根据你所要完成的是什么,你是靶向浏览器:

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

我一直在研究跨浏览器的解决方案,但没有取得太大的成功。你应该远离突变事件,因为它们不是跨浏览器和非常缓慢的。 他们被弃用的原因有很好的理由。如果您想了解更多阅读:

+0

我认为Mozilla家伙[完成你的工作](http://stackoverflow.com/a/13835369/237285)。 :) – 2012-12-12 08:15:56

31

是突变事件已被否决是因为巨大的性能问题的原因。

更换为突变观察,看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 
    }); 

这在Chrome 18和Firefox和Webkit每晚构建中都受支持。 Firefox 14也将支持这个功能。

+0

“选项”对象字面值中的分号应为逗号。 – Holf 2013-05-21 16:46:13

12

一年之后,DOM 4级有新的闪亮Mutation Observers(按照链接,他们解释了很多!)。如果一个Mutation Event发射了一千次,MutationObserver只有一次包含和可访问的所有修改触发。

Works的(作为2017/03):

  • 火狐14+
  • IE 11
  • 边缘
  • 歌剧15+
  • 铬26+(18至25为前缀, window.WebKitMutationObserver
  • Safari 6。0(前缀,window.WebKitMutationObserver
12

的弃用DOM一个伟大的替换*事件与CSS动画结合animationStart。关于该方法的David Walsh writes

首先,设置关键帧,并把它应用到你想监听的元素(不要忘了供应商前缀!):

@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; 
} 

接下来,添加监听器:

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 

Ta-da!这里是David's demo。它适用于我的Chrome扩展程序adds Facebook pictures to Google Voice(请参阅content.css和inject.js)。

+0

另请参阅[naugtur的伟大工作](http://stackoverflow.com/a/15328624/237285)。 – 2013-05-25 02:27:25

+0

顺便说一下。 'clip:rect'不会在IE10中触发事件。我前段时间修复了它 – naugtur 2014-02-03 12:01:11