使用 MutationObserver 在元素内的 dom 更改时调用函数非常容易,如下所示:
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
eventListenerSupported = window.addEventListener;
return function(obj, callback){
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
callback();
});
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
}
else if( eventListenerSupported ){
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
})();
observeDOM( $('#dom_element')[0] ,function(){
console.log('dom changed');
});
但是我希望它在'#dom_element'中的dom停止变化时做一些事情,或者如果几毫秒内没有变化。有没有办法做到这一点?