使用自定义事件跟踪属性更改

Tracking attribute change using custom event

我的问题是我想使用自定义事件跟踪元素上的属性更改,我一直在阅读有关 Mozilla 开发人员的资料,但我仍然不明白。

那么,自定义事件是如何运作的?以及如何使用它来跟踪属性 change/variable 的变化(class)。

Standard event listeners respond to many things, but element attribute changes are not one of them. A MutationObserver 确实是您自己构建这样的东西的唯一方法,缺少大量资源的 setInterval 假监听器。

var target = document.querySelector('button');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.attributeName + ' atrribute was changed.');
  });    
});

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

这是一个 JSFiddle,其中单击按钮会更改元素的颜色,该颜色由 MutationObserver 拾取。