jQuery SVG, why can't I addClass?

前端 未结 15 1831
失恋的感觉
失恋的感觉 2020-11-22 02:25

I am using jQuery SVG. I can\'t add or remove a class to an object. Anyone know my mistake?

The SVG:



        
15条回答
  •  一生所求
    2020-11-22 02:46

    Just add the missing prototype constructor to all SVG nodes:

    SVGElement.prototype.hasClass = function (className) {
      return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.getAttribute('class'));
    };
    
    SVGElement.prototype.addClass = function (className) { 
      if (!this.hasClass(className)) {
        this.setAttribute('class', this.getAttribute('class') + ' ' + className);
      }
    };
    
    SVGElement.prototype.removeClass = function (className) {
      var removedClass = this.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
      if (this.hasClass(className)) {
        this.setAttribute('class', removedClass);
      }
    };
    

    You can then use it this way without requiring jQuery:

    this.addClass('clicked');
    
    this.removeClass('clicked');
    

    All credit goes to Todd Moto.

提交回复
热议问题