前言
檢測一個原生dom的變化,如一個div的顏色,大小,所在位置,內部元素的屬性是否變化,更深層dom樹上的變化等等。
都可以使用一個window上暴露出來的一個api:MutationObserver
語法
官方地址:MutationObserver.MutationObserver() - Web API 接口參考 | MDN
使用new MutationObserver創建一個檢測實例
需要傳遞一個配置參數:檢測的范圍
返回值為一個新的、包含監聽 DOM 變化回調函數的?MutationObserver?對象。
function callback(mutationList, observer) {mutationList.forEach((mutation) => {switch (mutation.type) {case "childList":/* 從樹上添加或移除一個或更多的子節點;參見 mutation.addedNodes 與mutation.removedNodes */break;case "attributes":/* mutation.target 中某節點的一個屬性值被更改;該屬性名稱在 mutation.attributeName 中,該屬性之前的值為 mutation.oldValue */break;}});
}var targetNode = document.querySelector("#someElement");
var observerOptions = {childList: true, // 觀察目標子節點的變化,是否有添加或者刪除attributes: true, // 觀察屬性變動subtree: true, // 觀察后代節點,默認為 false
};var observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);
demo
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>mutationObserve的使用</title>
</head>
<style>body{position: relative;}.box{position: absolute;width: 30px;height: 30px;background: red;}
</style>
<body><div class="box" id="box"></div><button id="btn">向右移動</button><script>const box = document.getElementById('box')const btn = document.getElementById('btn')box.style.left = '10px'box.style.top = '100px'const boxMutationObserveHandler = new MutationObserver(function(mutationList,observe){mutationList.forEach((mutation)=>{console.log(mutation,'節點信息')if(mutation.target.id === 'box'){console.log(mutation.target.style.left,'box的left變化')}})})boxMutationObserveHandler.observe(box,{subtree:true,childList:true,attributes:true})btn.onclick = ()=>{console.log('點擊按鈕')box.style.left = parseInt(box.style.left)+5+'px'}</script>
</body>
</html>
?效果如下
?感覺還行的給個贊吧