具有特定突变的 MutationObserver

Ian*_*lor 1 javascript events mutation-observers

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

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

作为主要的 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');
    }
});
Run Code Online (Sandbox Code Playgroud)
#wrapper {
  height: 200px;
  overflow: scroll;
}
#foo {
  height: 1000px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
   <div id="foo">Element</div>
</div>
Run Code Online (Sandbox Code Playgroud)

Ian*_*lor 5

尽管 @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');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)
#wrapper {
  height: 200px;
  overflow: scroll;
}
#foo {
  height: 1000px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
   <div id="foo">Element</div>
</div>
Run Code Online (Sandbox Code Playgroud)

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