本文介绍了MutationObserver类更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using MutationObserver to detect when a specific class has been added to an element.

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 检查该类现在是否存在.似乎很杂乱

My question is: Is there a better way to verify that this is a newly added class? Currently I am using regex to check that the class didn't exist previously and classList to check that the class exists now. Seems messy

小提琴

推荐答案

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

@sliptype - You could do it in the below manner:

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

这篇关于MutationObserver类更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:32