MutationObserver类更改

时间:2018-03-09 20:53:35

标签: javascript mutation-observers

我正在使用MutationObserver来检测何时将特定类添加到元素中。

const observer = new MutationObserver((mutations) => { 
    mutations.forEach((mutation) => {
      const el = mutation.target;
      if ((!mutation.oldValue || !mutation.oldValue.match(/\bis-busy\b/)) 
        && mutation.target.classList 
        && mutation.target.classList.contains('is-busy')){
        alert('is-busy class added');
      }
    });
 });

observer.observe(document.querySelector('div'), { 
  attributes: true, 
  attributeOldValue: true, 
  attributeFilter: ['class'] 
});

我的问题是:有没有更好的方法来验证这是一个新添加的类?目前我正在使用正则表达式检查该类以前是否存在并且{{1现在检查该类是否存在。似乎凌乱

Fiddle

2 个答案:

答案 0 :(得分:1)

@sliptype-您可以按照以下方式进行操作:

const element = document.querySelector('div');
let prevState = element.classList.contains('is-busy');
const observer = new MutationObserver((mutations) => { 
    mutations.forEach((mutation) => {
        const { target } = mutation;

        if (mutation.attributeName === 'class') {
            const currentState = mutation.target.classList.contains('is-busy');
            if (prevState !== currentState) {
                prevState = currentState;
                console.log(`'is-busy' class ${currentState ? 'added' : 'removed'}`);
            }
        }
    });
});

答案 1 :(得分:0)

您可以尝试访问目标上的 classname 吗?

let observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        if (mutationRecord.target.className === "is-busy") {
            console.log("Class added....")

        } else {
            console.log("Class not added....")
        };
    })
});

let target = document.querySelector("your-div");

observer.observe(target, { attributes : true, attributeFilter : ['style', 'className'] });