<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script>
const div = document.querySelector("div");
const observer = new MutationObserver(function (mutations) {
mutations.forEach((record) => {
console.log(record);
});
});
observer.observe(div, {
childList: true,
attributes: true,
characterData: true,
});
function changeContent() {
div.textContent = "Hi I'm Tom";
}
function changeColor() {
div.style.color = "red";
}
</script>
</head>
<body>
<button onclick="changeContent()">改變內容</button>
<button onclick="changeColor()">改變顏色</button>
<div>Hi I'm Max</div>
</body>
</html>
簡單說他可以偵測DOM的變化,有變化就觸發方法,以現在前端框架滿天飛的時代,好像沒啥鳥用,不過有趣就記錄一下。
沒有留言:
張貼留言