Is it possible to listen to a “style change” event?

前端 未结 11 1232
南笙
南笙 2020-11-22 08:03

Is it possible to create an event listener in jQuery that can be bound to any style changes? For example, if I want to \"do\" something when an element changes dimensions, o

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 08:45

    Things have moved on a bit since the question was asked - it is now possible to use a MutationObserver to detect changes in the 'style' attribute of an element, no jQuery required:

    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'] });
    

    The argument that gets passed to the callback function is a MutationRecord object that lets you get hold of the old and new style values.

    Support is good in modern browsers including IE 11+.

提交回复
热议问题