MutationObserver 监听dom 变化api

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button onclick="add()">add</button>
    <textarea id="app">
     
    </textarea>
    <script>
      // 选择需要观察变动的节点
      const targetNode = document.getElementById("app");

      // 观察器的配置(需要观察什么变动)
      const config = { attributes: true, childList: true, subtree: true };

      function add() {
        let odiv = document.createElement("div");
        odiv.innerHTML = "my name odiv";
        targetNode.appendChild(odiv);
      }

      // 当观察到变动时执行的回调函数
      const callback = function (mutationsList, observer) {
        console.log(mutationsList, observer, "========");
        // Use traditional 'for loops' for IE 11
        for (let mutation of mutationsList) {
          if (mutation.type === "childList") {
            console.log("A child node has been added or removed.");
          } else if (mutation.type === "attributes") {

            console.log(

              "The " + mutation.attributeName + " attribute was modified." 
              ,targetNode.style.width,targetNode.style.height,mutation.target.style.value,
            );
          }
        }
      };

      // 创建一个观察器实例并传入回调函数
      const observer = new MutationObserver(callback);

      // 以上述配置开始观察目标节点
      observer.observe(targetNode, config);

      // 之后,可停止观察
    //   observer.disconnect();
    </script>
  </body>
</html>

参考链接:https://javascript.ruanyifeng.com/dom/mutationobserver.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />

    <title>
      CodePen - Mutation Observer &amp; customize resize event listener &amp;
      demo
    </title>
  </head>

  <body translate="no">
    <!DOCTYPE html>
    <html lang="zh-Hans">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <meta name="author" content="xgqfrms" />
        <meta name="generator" content="VS code" />
        <title>
          Mutation Observer & customize resize event listener & demo
        </title>
        <style>
          ol {
            box-sizing: border-box;
            width: 110px;
            height: 110px;
            border: 1px solid red;
            padding: 10px;
            resize: both;
            overflow: auto;
          }
        </style>
      </head>

      <body>
        <section>
          <h1>Mutation Observer & customize resize event listener & demo</h1>
        </section>
        <section>
          <ol contenteditable oninput="">
            <li>Press enter</li>
          </ol>
        </section>
        <!-- js -->
        <script>
          const MutationObserver =
            window.MutationObserver ||
            window.WebKitMutationObserver ||
            window.MozMutationObserver;
          // target
          const list = document.querySelector(`ol`);
          // options
          const config = {
            attributes: true,
            childList: true,
            characterData: true,
            subtree: true,
          };
          // instance
          const observer = new MutationObserver(function (mutations) {
            // console.log(`mutations =`, mutations); // MutationRecord
            mutations.forEach(function (mutation) {
              // console.log("mutation =", mutation);
              if (mutation.type === "characterData") {
                // target & object === typeof(mutation.target)
                // console.log("A child node has been added OR removed.", mutation.target, typeof(mutation.target));
                // console.log("[...mutation.addedNodes].length", [...mutation.addedNodes].length);
                // console.log("[...mutation.removedNodes].length", [...mutation.removedNodes].length);
                // if (mutation.target && [...mutation.addedNodes].length) {
                //     // [...mutation.addedNodes].length
                //     console.log(`A child node ${mutation.target} has been added!`, mutation.target);
                // }
                // if (mutation.target && [...mutation.removedNodes].length) {
                //     // [...mutation.removedNodes].length
                //     console.log(`A child node ${mutation.target} has been removed!`, mutation.target);
                // }
              }
              if (mutation.type === "childList") {
                if (mutation.target && [...mutation.addedNodes].length) {
                  console.log(
                    `A child node ${mutation.target} has been added!`,
                    mutation.target
                  );
                }
                if (mutation.target && [...mutation.removedNodes].length) {
                  console.log(
                    `A child node ${mutation.target} has been removed!`,
                    mutation.target
                  );
                }
                // do somwthings
                let list_values = [];
                list_values = [].slice
                  .call(list.children)
                  .map(function (node) {
                    return node.innerHTML;
                  })
                  .filter(function (str) {
                    if (str === "<br>") {
                      return false;
                    } else {
                      return true;
                    }
                  });
                console.log(list_values);
              }
              if (mutation.type === "attributes") {
                console.log("mutation =", mutation);
                console.log(
                  `The \`${mutation.attributeName}\` attribute was modified.`
                );
                // console.log("list style =", list.style);
                let { width, height } = list.style;
                let style = {
                  width,
                  height,
                };
                console.log("style =\n", JSON.stringify(style, null, 4));
              }
            });
          });
          observer.observe(list, config);
          // 相关属性 dom
          // Later, you can stop observing
          // setTimeout(() => {
          //     observer.disconnect();
          // }, 1000 * 100);
          // bug ??? after disconnect
          // list.attributes;
          // list.setAttribute(`style`, `height: 212px; width: 213px;`);
          // list.setAttribute(`data-test`, `666`);
          // list.removeAttribute(`data-test`);
          // list.children;
          // list.childElementCount;
          // list.childNodes;
          // list.hasChildNodes();
          // list.firstElementChild;
          // list.firstChild;
          // list.removeChild(li);
          // list.removeChild(list.firstElementChild);
          // list.replaceChild(li, li);
          // list.replaceChild(list.firstElementChild, list.lastElementChild);
        </script>
      </body>
    </html>
  </body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值