CSS属性更改侦听器

时间:2012-08-30 16:24:25

标签: javascript css

CSS属性更改侦听器的任何建议实现?也许:

thread =

function getValues(){
  while(true){
    for each CSS property{
      if(properties[property] != nil && getValue(property) != properties[property]){alert('change')}
      else{properties[property] = getValue(property)}
    }
  }
}

2 个答案:

答案 0 :(得分:3)

我认为你正在寻找这个:

document.documentElement.addEventListener('DOMAttrModified', function(e){
  if (e.attrName === 'style') {
    console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
  }
}, false);

如果你谷歌,它会出现一堆东西。这看起来很有希望:

  

http://darcyclarke.me/development/detect-attribute-changes-with-jquery/

答案 1 :(得分:2)

不推荐使用DOMAttrModified等变种事件。请考虑使用MutationObserver。

示例:

<div>use devtools to change the <code>background-color</code> property of this node to <code>red</code></div>
<p>status...</p>

JS:

var observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.target.style.color === 'red') {
      document.querySelector('p').textContent = 'success';
    }
  });
});

var observerConfig = {
  attributes: true,
  childList: false,
  characterData: false,
  attributeOldValue: true
};

var targetNode = document.querySelector('div');
observer.observe(targetNode, observerConfig);