Firing events on CSS class changes in jQuery

后端 未结 13 1109
天涯浪人
天涯浪人 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 04:52

    IMHO the better solution is to combine two answers by @RamboNo5 and @Jason

    I mean overridding addClass function and adding a custom event called cssClassChanged

    // Create a closure
    (function(){
        // Your base, I'm in it!
        var originalAddClassMethod = jQuery.fn.addClass;
    
        jQuery.fn.addClass = function(){
            // Execute the original method.
            var result = originalAddClassMethod.apply( this, arguments );
    
            // trigger a custom event
            jQuery(this).trigger('cssClassChanged');
    
            // return the original result
            return result;
        }
    })();
    
    // document ready function
    $(function(){
        $("#YourExampleElementID").bind('cssClassChanged', function(){ 
            //do stuff here
        });
    });
    

提交回复
热议问题