<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<div id="root">aaaaa</div>
</body>
</html>
<script>
// 监听对象属性的变换.
var targetNode= document.getElementById("root");
console.log(targetNode);
//需要监听的属性.
// 节点本身属性的检查, 子节点列表, 子树的变换.
var config={attributes:true,childList:true,subtree:true};
// 使用定时器修改对象的属性,
var callback = function(mutationsList,observer){
//console.log(mutationsList);
//console.log(observer);
for(var mutation of mutationsList)
{
if (mutation.type=='childList')
{
console.log("this is childlist change");
}else if(mutation.type=='attributes')
{
console.log("this is attributes");
}else{
console.log("this is subtree");
}
}
};
var observer = new MutationObserver(callback);
observer.observe(targetNode,config);
// 清楚要监听的内容.
// setTimeout和setInterval
// 为了测试自动化.
setTimeout(function(){
console.log(targetNode);
targetNode.setAttribute("style","color:red;");
},2000);
// 这个不可以在属性修改前,否则没有效果,
//observer.disconnect();
</script>
具体的函数定义, 主要是observe的第二个参数的说明.