观察元素更改
ts
function observe(
callback: (
mutations: {
addedNodes: Node[];
targetNodes: Node[];
attributeName: string | null;
attributeNamespace: string | null;
nextSibling: Node | null;
oldValue: string | null;
previousSibling: Node | null;
removedNodes: Node[];
target: Node;
type: MutationRecordType;
}[],
observer: MutationObserver
) => void,
target: Node,
options?: MutationObserverInit
) {
function getAll(...nodes: Node[]) {
const tmp = [...nodes];
for (let i = 0; i < tmp.length; i++) {
tmp.push(...tmp[i].childNodes);
}
return tmp;
}
const observer = new MutationObserver((mutationsList) => {
callback(
mutationsList.map((mutation) => {
let _addedNodes: Node[] | null = null;
let _removedNodes: Node[] | null = null;
let _targetNodes: Node[] | null = null;
return {
type: mutation.type,
target: mutation.target,
attributeName: mutation.attributeName,
attributeNamespace: mutation.attributeNamespace,
oldValue: mutation.oldValue,
nextSibling: mutation.nextSibling,
previousSibling: mutation.previousSibling,
get addedNodes() {
_addedNodes ??= getAll(...mutation.addedNodes);
return _addedNodes;
},
get removedNodes() {
_removedNodes ??= getAll(...mutation.removedNodes);
return _removedNodes;
},
get targetNodes() {
_targetNodes ??= getAll(mutation.target);
return _targetNodes;
},
};
}),
observer
);
});
observer.observe(target, options);
return observer;
}