且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测chrome中的元素样式更改

更新时间:2022-10-16 07:55:13

您应该可以通过 MutationObserver

a> - 请参阅 演示 (仅适用于Webkit),这是一种全新的闪亮方式收到有关DOM变化的通知。较旧的,现在已被弃用的方式是突变事件

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

strong>
 < p id =observablestyle =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);

//点击事件来改变我们正在观察的事物的颜色
target.addEventListener('click',function(ev){
observable.style.color ='green ';
返回false;
},false);

归功于这篇博客文章,以上部分代码。


I'm trying to find a way to detect changes to the element style but I haven't had much luck. The code below works on a new property I define like tempBgColor but I cannot override/shadow an existing property like color. I know jquery has a watch function, but it only detects changes from the jquery api but not directly changing the value of a style something like 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 + "!");
});

Any pointers?

You should be able to do this with a MutationObserver - see demo (Webkit only), which is the new, shiny way of getting notified about changes in the DOM. The older, now deprecated, way was Mutation events.

Demo simply logs in the console the old and new values when the paragraph is clicked. Note that the old value will not be available if it was set via a non-inline CSS rule, but the change will still be detected.

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);

Credit to this blog post, for some of the code above.