首页  >  文章  >  web前端  >  如何检测 DOM 中的属性更改?

如何检测 DOM 中的属性更改?

Patricia Arquette
Patricia Arquette原创
2024-10-26 16:59:03409浏览

How can I detect Attribute Changes in the DOM?

检测 DOM 中的属性更改

问题:

是否可以启动事件,例如自定义事件,当 HTML 元素的属性发生更改时?更具体地说,当图像 (如何检测 DOM 中的属性更改?) 元素的 src 属性或分区 (

) 元素的 innerHTML 属性被修改时?

答案:

突变事件(已弃用)

历史上,DOM 突变事件用于监视属性更改。然而,它们自 2012 年以来已被弃用。建议使用它们的替代品 MutationObserver。

MutationObserver

MutationObserver 是一个高级 API,使您能够观察 DOM 的更改。它提供比突变事件更细粒度的控制,并允许您跟踪特定元素、突变和树结构。

MutationObserver 示例:

<code class="javascript">// Create a new MutationObserver instance
const observer = new MutationObserver((mutationsList) => {
  for (const mutation of mutationsList) {
    // Check if the mutation is an attribute change
    if (mutation.type === "attributes") {
      console.log(`Attribute changed on ${mutation.target.nodeName}`);
    }
  }
});

// Start observing the document body for attribute changes
observer.observe(document.body, { attributes: true });</code>

jQuery 事件插件

jQuery 的 Mutation Events 插件也可用于检测属性更改。它为基本用例提供了更易于使用的 API。

jQuery 突变事件插件示例:

<code class="javascript">$("img").on("attrchange", (e) => {
  console.log(`Image src changed to ${e.target.src}`);
});</code>

注意:

浏览器对 DOM 突变事件的支持各不相同。始终建议在依赖此功能之前检查兼容性。

以上是如何检测 DOM 中的属性更改?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn