相信前端开发同学都熟悉各种各样的监听事件,比如元素点击事件onClick,鼠标事件onMouseDown、onMouseHover,键盘按键onKeyDown,浏览器窗口改变事件onResize等等。
那我们如何监听页面某个元素的属性变化呢?
window.MutationObserver(callback)
该接口用来观察节点变化,MutationObserver是一个构造器,接收一个回调函数callback用来处理节点变化时所做的操作。
var observe = new MutationObserver(mutationCallback);
MutationObserver对象有三个方法,分别如下:
- observe:设置观察目标,接受两个参数:target:观察目标,config:设置观察选项
var observe = new MutationObserver(mutationCallback);
observe.observe(dom, config);// 后面介绍config的配置
- disconnect:阻止对目标节点的监听。
var observe = new MutationObserver(mutationCallback);
observe.disconnect();
- takeRecords:取出记录队列中的记录。它的一个作用是当你不想对节点变化立刻做出反应,过段时间再显示改变了节点的内容。
var observe = new MutationObserver(mutationCallback);
var record = observe.takeRecords();
config配置(只介绍常用的几个):
let config = {
attributes: true, //目标节点的属性变化
childList: true, //目标节点的子节点的新增和删除
characterData: true, //如果目标节点为characterData节点(一种抽象接口,具体可以为文本节点,注释节点,以及处理指令节点)时,也要观察该节点的文本内容是否发生变化
subtree: true, //目标节点所有后代节点的attributes、childList、characterData变化
};
callback 示例:
const mutationCallback = (mutationsList) => {
for(let mutation of mutationsList) {
let type = mutation.type;
switch (type) {
case "childList":
console.log("A child node has been added or removed.");
break;
case "attributes":
console.log(`The ${mutation.attributeName} attribute was modified.`);
break;
case "subtree":
console.log(`The subtree was modified.`);
break;
default:
break;
}
}
};