2011-03-24 61 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