Firing events on CSS class changes in jQuery

后端 未结 13 902
天涯浪人
天涯浪人 2020-11-22 04:45

How can I fire an event if a CSS class is added or changed using jQuery? Does changing of a CSS class fire the jQuery change() event?

相关标签:
13条回答
  • 2020-11-22 05:13

    If you want to detect class change, best way is to use Mutation Observers, which gives you complete control over any attribute change. However you need to define listener yourself, and append it to element you are listening. Good thing is that you don't need to trigger anything manually once listener is appended.

    $(function() {
    (function($) {
        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    
        $.fn.attrchange = function(callback) {
            if (MutationObserver) {
                var options = {
                    subtree: false,
                    attributes: true
                };
    
                var observer = new MutationObserver(function(mutations) {
                    mutations.forEach(function(e) {
                        callback.call(e.target, e.attributeName);
                    });
                });
    
                return this.each(function() {
                    observer.observe(this, options);
                });
    
            }
        }
    })(jQuery);
    
    //Now you need to append event listener
    $('body *').attrchange(function(attrName) {
    
        if(attrName=='class'){
                alert('class changed');
        }else if(attrName=='id'){
                alert('id changed');
        }else{
            //OTHER ATTR CHANGED
        }
    
    });
    });
    

    In this example event listener is appended to every element, but you don't want that in most cases (save memory). Append this "attrchange" listener to element you want observe.

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