我正在使用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']
});

我的问题是:是否有更好的方法来验证这是一个新添加的类? 当前,我正在使用正则表达式检查该类以前是否不存在,使用classList检查该类现在是否存在。看起来很杂乱

Fiddle

最佳答案

@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'}`);
            }
        }
    });
});

关于javascript - MutationObserver类更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49201984/

10-11 02:34