首页 > 解决方案 > 使用 MutationObserver 检测类更改?

问题描述

我有一个<body>电话<body id="check-in-body">,我想检测课程何时更改。它可以从class="theme-1"to改变class="theme-2"等等。

我有下面的代码,但我不能让它工作。在从下面的代码中删除&& (mutation.attributeName === "class")和删除时,我能够使其部分工作。attributeFilter: ['class']但这一直触发,因为当我有一个可见的模态时style="overflow: hidden;"body我认为这就是触发它的原因。我如何只听班级变化body

function searchBackgroundFetch() {
  var element = document.querySelector('#check-in-body');
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if ((mutation.type === "attributes") && (mutation.attributeName === "class")) {
        console.log('Yeah');
      }
    });
  });
  observer.observe(element, {
    attributes: true,
    attributeFilter: ['class']
  });
}

标签: jquerymutation-observers

解决方案


推荐阅读