Set style change event listener in Javascript

后端 未结 2 1089
旧巷少年郎
旧巷少年郎 2021-01-26 07:17

My div looks something like this:

相关标签:
2条回答
  • 2021-01-26 07:32

    You can use MutationObserver

    Then code example:

    var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        console.log('style changed!');
       });    
     });
    
     var target = document.getElementById('myId');
      observer.observe(target, { attributes : true, attributeFilter : ['style'] });
    

    Note: this only works with inline styles(any changing of styles), not when the style changes as a consequence of class change or @media change This is a answer https://stackoverflow.com/a/20683311/3344953

    0 讨论(0)
  • 2021-01-26 07:57

    It's possible with MutationObserver, but it's a somewhat odd thing to do:

    console.log('Script start');
    const div = document.querySelector('div');
    
    const o = new MutationObserver(() => {
      console.log('style changed');
    });
    o.observe(div, { attributes: true, attributeFilter: ["style"] });
    
    setTimeout(() => {
      div.style.backgroundImage = 'url(https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=48&d=identicon&r=PG&f=1)';
    }, 500);
    <div tabindex="0" role="button" id="profile-pic" style="background-image: 'Some url';">xx</div>

    It would make a lot more sense for the function that makes the style change to call other functions that need to know that the change happened.

    0 讨论(0)
提交回复
热议问题