DOM状态监听(观察者模式)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript监听DOM内容改变事件</title>
<style type="text/css">
#el-test{
line-height: 100px;
width: 200px;
border: #fff solid 1px;
text-align: center;
}
</style>
</head>
<body>
<div id="el-test">QQ 183672812</div>

<script type="text/javascript">
// 选中观察突变的节点
var targetNode = document.getElementById('el-test');

// 观察者的选项(要观察哪些突变)
var config = { attributes: true, characterData: true, childList: true, subtree: true, attributeOldValue: true, characterDataOldValue: true };

// 当观察到突变时执行的回调函数
var callback = function(mutationsList) {
mutationsList.forEach(function(item,index,arr){
if (item.type == 'childList') {
console.log('有节点发生变化,当前节点的内容是:');
console.log(item.target.innerHTML);
} else if (item.type == 'attributes') {
console.log(item.attributeName+'-----属性item.attributeName 发生了变化');
}
});
};

// 创建一个链接到回调函数的观察者实例
var observer = new MutationObserver(callback);

// 开始观察已配置突变的目标节点
observer.observe(targetNode, config);

// 停止观察
//observer.disconnect();
</script>
</body>
</html>

posted @ 2020-09-11 09:58  A影子放風箏  阅读(479)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css