Detect element style change in chrome

后端 未结 3 677
闹比i
闹比i 2021-01-02 11:52

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

3条回答
  •  时光说笑
    2021-01-02 12:09

    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

    Lorem ipsum

    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.

提交回复
热议问题