检测chrome中的元素样式更改

时间:2012-11-26 13:56:53

标签: javascript google-chrome

我正试图找到一种方法来检测元素样式的变化,但我没有太多运气。下面的代码适用于我定义的新属性,如tempBgColor,但我不能覆盖/遮蔽像color这样的现有属性。我知道jquery有一个watch函数,但它只检测jquery api的变化,但不直接改变elem.style.color等样式的值。

var e = document.getElementById('element');
e.style.__defineGetter__("color", function() {
   return "A property";
});
e.style.__defineSetter__("color", function(val) {
    alert("Setting " + val + "!");
});

任何指针?

3 个答案:

答案 0 :(得分:16)

您应该可以使用MutationObserver执行此操作 - 请参阅demo(仅限Webkit),这是获取有关DOM更改通知的新方法。旧的,现已弃用的方式为Mutation events

演示只需在单击段落时在控制台中登录旧值和新值。请注意,如果通过非内联CSS规则设置旧值,则旧值将不可用,但仍将检测到更改。

<强> HTML

<p id="observable" style="color: red">Lorem ipsum</p>​

<强>的JavaScript

var MutationObserver = window.WebKitMutationObserver;

var target = document.querySelector('#observable');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log('old', mutation.oldValue);
    console.log('new', mutation.target.style.cssText);
  });    
});

var config = { attributes: true, attributeOldValue: true }

observer.observe(target, config);

// click event to change colour of the thing we are observing
target.addEventListener('click', function(ev) {
    observable.style.color = 'green';
    return false;
}, false);

感谢this blog post,对于上面的一些代码。

答案 1 :(得分:8)

打开Chrome的开发者工具后,您可以找到您感兴趣的样式更改的元素,右键单击它,选择“Break on ...”和“Attributes modification”。

答案 2 :(得分:1)

这是一个使用setTimeout和unexcorejs的简单实现。

找出所做更改的唯一方法是遍历样式对象属性。

这是实时example

$( function () {
  var ele = document.getElementById('ele'), 
      oldStyle = {};

function checkEquality() {
  style = _.clone(ele.style);
  if (!_.isEqual(style, oldStyle)) {
    console.log('Not equal');
    oldStyle = _.clone(style);
  } else {
    console.log('Equal');
  }
  _.delay(checkEquality, 2000);
}

checkEquality();

$('a#add_prop').on('click', function () {
  var props = $('#prop').val().replace(/ /g, '').split(':');
  console.log(props);
  $(ele).css(props[0], props[1]);
});

$('#prop').on('keydown', function (e) {
  if (e.keyCode == 13) {
    $('a#add_prop').trigger('click');    
  }
});

});