Firing events on CSS class changes in jQuery

后端 未结 13 924
天涯浪人
天涯浪人 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:11

    Just a proof of concept:

    Look at the gist to see some annotations and stay up-to-date:

    https://gist.github.com/yckart/c893d7db0f49b1ea4dfb

    (function ($) {
      var methods = ['addClass', 'toggleClass', 'removeClass'];
    
      $.each(methods, function (index, method) {
        var originalMethod = $.fn[method];
    
        $.fn[method] = function () {
          var oldClass = this[0].className;
          var result = originalMethod.apply(this, arguments);
          var newClass = this[0].className;
    
          this.trigger(method, [oldClass, newClass]);
    
          return result;
        };
      });
    }(window.jQuery || window.Zepto));
    

    The usage is quite simple, just add a new listender on the node you want to observe and manipulate the classes as usually:

    var $node = $('div')
    
    // listen to class-manipulation
    .on('addClass toggleClass removeClass', function (e, oldClass, newClass) {
      console.log('Changed from %s to %s due %s', oldClass, newClass, e.type);
    })
    
    // make some changes
    .addClass('foo')
    .removeClass('foo')
    .toggleClass('foo');
    

提交回复
热议问题