JS| MutationObserver

2024-10-09  本文已影响0人  玫瑰的lover

观察 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,
  });
};
上一篇 下一篇

猜你喜欢

热点阅读