」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何偵測和回應 DOM 屬性變更:MutationObserver 與傳統方法?

如何偵測和回應 DOM 屬性變更:MutationObserver 與傳統方法?

發佈於2024-11-02
瀏覽:439

How to Detect and Respond to DOM Attribute Changes: MutationObserver vs. Legacy Methods?

DOM 屬性變化觸發事件

許多場景需要偵測 DOM 屬性的變化,例如圖片來源變更或 div 的 HTML 變更內容更新。瀏覽器對此功能的支援隨著時間的推移而不斷發展。

DOM 突變事件(舊版)

過去,DOM 突變事件提供了一種偵聽屬性變更的方法。這些事件包括:

  • DOMAttrModified
  • DOMNodeInserted
  • DOMNodeRemoved

但是,瀏覽器對DOM Mutation 事件的支援不一致,導致&&&&]

但是,瀏覽器對DOM Mutation 事件的支援不一致,導致已於2012 年棄用。

MutationObserver API

作為 DOM Mutation Events 的替代品,引入了 MutationObserver API。 MutationObserver 提供了一種更強大且廣受支援的方法來偵測 DOM 屬性和 DOM 其他方面的變更。

使用 MutationObserver,您可以建立觀察者實例並指定要監視的變更類型。當 DOM 中發生任何符合的變更時,觀察者將通知您。

以下是如何使用 MutationObserver 偵測影像來源屬性變更的範例:
// Create an observer instance
const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    // Check if the mutation is for the "src" attribute
    if (mutation.attributeName === "src") {
      // Do something in response to the source change
    }
  }
});

// Start observing the specified target node
observer.observe(image, { attributes: true, attributeFilter: ["src"] });
// Create觀察者實例 const 觀察者 = new MutationObserver((mutations) => { for (突變的常數突變) { // 檢查突變是否針對「src」屬性 if (mutation.attributeName === "src") { // 回應來源更改做一些事情 } } }); // 開始觀察指定目標節點 observe(image, { attribute: true, attributeFilter: ["src"] });

在本例中,觀察者被配置為監視影像節點的src 屬性,並將呼叫指定的回呼

jQuery Mutation Events 外掛程式

如果您使用jQuery,您可以利用其Mutation Events 外掛程式作為MutationObserver 的替代品。該外掛提供了一個用於處理 DOM 屬性變更的簡化介面,如果您只對特定屬性變更感興趣,則該外掛程式非常有用。
// Create an observer instance
const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    // Check if the mutation is for the "src" attribute
    if (mutation.attributeName === "src") {
      // Do something in response to the source change
    }
  }
});

// Start observing the specified target node
observer.observe(image, { attributes: true, attributeFilter: ["src"] });
$(image).on("DOMAttrModified", (event) = > { if (event.attrName === "src") { // 回應來源更改做一些事情 } });

透過利用 MutationObserver 或 jQuery Mutation Events 插件,您可以有效地檢測 DOM 屬性中的變更並執行自訂操作來回應這些變更。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3