赞
踩
相信前端开发同学都熟悉各种各样的监听事件,比如元素点击事件onClick,鼠标事件onMouseDown、onMouseHover,键盘按键onKeyDown,浏览器窗口改变事件onResize等等。
那我们如何监听页面某个元素的属性变化呢?
该接口用来观察节点变化,MutationObserver是一个构造器,接收一个回调函数callback用来处理节点变化时所做的操作。
var observe = new MutationObserver(mutationCallback);
MutationObserver对象有三个方法,分别如下:
var observe = new MutationObserver(mutationCallback);
observe.observe(dom, config);// 后面介绍config的配置
var observe = new MutationObserver(mutationCallback);
observe.disconnect();
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; } } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。