jQuery SVG, why can't I addClass?

前端 未结 15 1848
失恋的感觉
失恋的感觉 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:57

    jQuery does not support the classes of SVG elements. You can get the element directly $(el).get(0) and use classList and add / remove. There is a trick with this too in that the topmost SVG element is actually a normal DOM object and can be used like every other element in jQuery. In my project I created this to take care of what I needed but the documentation provided on the Mozilla Developer Network has a shim that can be used as an alternative.

    example

    function addRemoveClass(jqEl, className, addOrRemove) 
    {
      var classAttr = jqEl.attr('class');
      if (!addOrRemove) {
        classAttr = classAttr.replace(new RegExp('\\s?' + className), '');
        jqEl.attr('class', classAttr);
      } else {
        classAttr = classAttr + (classAttr.length === 0 ? '' : ' ') + className;
        jqEl.attr('class', classAttr);
      }
    }
    

    An alternative all tougher is to use D3.js as your selector engine instead. My projects have charts that are built with it so it's also in my app scope. D3 correctly modifies the class attributes of vanilla DOM elements and SVG elements. Though adding D3 for just this case would likely be overkill.

    d3.select(el).classed('myclass', true);
    

提交回复
热议问题