具有特定突变的 MutationObserver

MutationObserver with specific mutations

我目前正在尝试使用 MutationObserver API 根据元素的 class 更改来触发消息(稍后将成为函数)。

我目前正在触发有关突变更改的日志,但我假设有 DOM 位置等正在触发的突变。有没有办法让 MutationObserver 只查找特定的 attributes 在这种情况下 class?

作为主要的 Drupal 开发人员,我习惯使用 jQuery,这就是为什么我有 classList 函数,因为我喜欢链接。

这是我的代码:

var foo = document.getElementById("foo");
var wrapper = document.getElementById("wrapper");

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.attributeName === "class") {
         var attributeValue = mutation.target.getAttribute(mutation.attributeName);
            console.log("Class attribute changed to:", attributeValue);
        }
    });
});

function classList(el) {
  var list = el.classList;
  return {
      add: function(c) { 
         if (!list.contains(c)){
            console.log('Contains: '+list.contains(c));
           list.add(c); 
         }
         return this;
      },
      remove: function(c) { 
         if (!list.contains(c)){ 
            list.remove(c); 
         }
         return this; 
      }
  };
}

observer.observe(foo,  {
    attributes: true
});

wrapper.addEventListener("scroll",function(){
    classList(foo).add('red').remove('yellow');
    if(wrapper.scrollTop > 500){
         classList(foo).add('yellow').remove('red');
    }
});
#wrapper {
  height: 200px;
  overflow: scroll;
}
#foo {
  height: 1000px;
}
<div id="wrapper">
   <div id="foo">Element</div>
</div>

虽然@wOxxOm 在他的评论中回答了我的问题(疏忽),但我应用了这个功能并意识到我不再需要 forEach 因为我只需要一个单一的属性,所以完成的(测试)代码如下所示:

var foo = document.getElementById("foo");
var wrapper = document.getElementById("wrapper");

var observer = new MutationObserver(function(mutation) {
    console.log('Current class:' + mutation[0].target.className);
});

observer.observe(foo, {
    attributes: true,
    attributeFilter: ['class']
});

wrapper.addEventListener("scroll",function(){
    if(wrapper.scrollTop > 500){
        if(!foo.classList.contains('yellow')){
           foo.classList.add('yellow');
           foo.classList.remove('red');
        }
    } else {
        if(!foo.classList.contains('red')){
           foo.classList.add('red');
           foo.classList.remove('yellow');
        }
    }
});
#wrapper {
  height: 200px;
  overflow: scroll;
}
#foo {
  height: 1000px;
}
<div id="wrapper">
   <div id="foo">Element</div>
</div>

我已经整理了突变观察器以找到class名称。我删除了我的函数以允许我链接 class 元素,因为我遇到了一个问题,即使 class 没有改变它也会触发突变,只是因为元素被返回。