MutationObserver的使用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div1{width: 200px;height: 200px;background-color: brown;}
#div2{width: 100px;height: 100px;background-color: rgb(165, 42, 134);}
</style>
</head>
<body>
<div id="div1">
<div id="div2">div2</div>
<a id="link" href="http://baidu.com">link</a>
<input type="text" id="txt">
</div>
<script>
/* var div1=document.getElementById("div1");
var div2=document.getElementById("div2");
var link=document.getElementById("link");
var txt=document.getElementById("txt");
div1.onclick=function(e){
alert("div1");
};
div2.onclick=function(e){
console.log(e.cancelable)
e.preventDefault();
alert("div2");
e.stopPropagation();
};
link.onclick=function(e){
console.log(e.cancelable)
e.preventDefault();
alert("link");
};
txt.onkeypress=function(e){
// console.log(e.cancelable)
console.log("onkeypress",e.keyCode);
};
txt.onkeydown=function(e){
// console.log(e.cancelable)
console.log(e.type,e.keyCode);
};
document.onclick=function(e){
console.log(e.type,e.clientX,e.clientY);
console.log(e.type,e.pageX,e.pageY);
console.log(e.type,e.screenX,e.screenY);
};
*/
// 创建观察实例
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
if (mutation.type === 'childList') {
console.log('子节点变化');
}
});
console.log('变化');
});
// 配置观察选项
const config = {
attributes: true,
childList: true,
subtree: true
};
// 开始观察目标节点
observer.observe(document.getElementsByTagName('body')[0], config);
</script>
</body>
</html>