JS| MutationObserver
2024-10-09 本文已影响0人
玫瑰的lover
- 创建并返回一个新的 MutationObserver 它会在指定的
DOM发生变化时被调用
观察 inputDom 的变化,运行副作用
export const useTagWidth = (field: string, setTagWith: (v: number) => void) => {
useEffect(() => {
const tagDom = document.querySelector(`#${field}`);
if (!tagDom) {
return;
}
const observer = new MutationObserver(() => {
const _tag = document.querySelector(
`#${field} .debug-i18n-select-input-inner .debug-i18n-tag`
);
setTagWith(_tag?.scrollWidth ?? 0);
});
observer.observe(tagDom, {
childList: true,
});
return () => {
return observer.disconnect();
};
}, [field, setTagWith]);
};
指定位置插入Logo
export const insertLogo = () => {
const devID = "dev-logo";
function appendDev2Header() {
const headerDom = document.querySelector("header .biz-logo");
if (!headerDom) return
const devLogo = Object.assign(document.createElement("span"), {
id: devID,
style: "font-size: 0; line-height: 1",
innerHTML:
'<svg >xxx</svg>',
});
headerDom.appendChild(devLogo);
}
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (
mutation.type === "childList" &&
!document.querySelector(`#${devID}`)
) {
appendDev2Header();
}
});
});
// 首次插入
appendDev2Header();
// 递归监听
observer.observe(document.body, {
childList: true,
subtree: true,
});
};