MutationObserver 是一個可以監(jiān)聽DOM結(jié)構(gòu)變化的接口。
官方使用方式示例
//選擇一個需要觀察的節(jié)點(diǎn)
var targetNode = document.getElementById('some-id');
// 設(shè)置observer的配置選項(xiàng)
var config = { attributes: true, childList: true, subtree: true };
// 當(dāng)節(jié)點(diǎn)發(fā)生變化時的需要執(zhí)行的函數(shù)
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// 創(chuàng)建一個observer示例與回調(diào)函數(shù)相關(guān)聯(lián)
var observer = new MutationObserver(callback);
//使用配置文件對目標(biāo)節(jié)點(diǎn)進(jìn)行觀測
observer.observe(targetNode, config);
// 停止觀測
observer.disconnect();
示例引用鏈接 https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
使用方式詳解
<!DOCTYPE html>
<div id="opop">
<div class="op"></div>
<div class="op"></div>
<div class="op op-node-change"></div>
</div>
<!--引用jqery-->
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script>
var targetNode =document.getElementById('opop');
var observer = new MutationObserver(function(mutations) {
var $node = $('#opop .op:not(.op-node-change)');
$node.addClass('op-node-change test');
console.log(111111);
});
observer.observe(targetNode, { attributes: true, childList: true, subtree: true });
</script>
上述代碼是一個簡單的應(yīng)用示例侮叮, 是在id="opop"下讨阻,給所有的沒有"op-node-change"的div 增加類"op-node-change test"
這段代碼直接運(yùn)行后的顯示
可以看到div 的類名并沒有發(fā)生改變治宣。此時,在Console中動態(tài)的增加新的節(jié)點(diǎn)
然后可以看到div 的類名發(fā)生了我們所期待的變化。