jQuery SVG, why can't I addClass?

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

    jQuery 2.2 supports SVG class manipulation

    The jQuery 2.2 and 1.12 Released post includes the following quote:

    While jQuery is a HTML library, we agreed that class support for SVG elements could be useful. Users will now be able to call the .addClass(), .removeClass(), .toggleClass(), and .hasClass() methods on SVG. jQuery now changes the class attribute rather than the className property. This also makes the class methods usable in general XML documents. Keep in mind that many other things will not work with SVG, and we still recommend using a library dedicated to SVG if you need anything beyond class manipulation.

    Example using jQuery 2.2.0

    It tests:

    • .addClass()
    • .removeClass()
    • .hasClass()

    If you click on that small square, it will change its color because the class attribute is added / removed.

    $("#x").click(function() {
        if ( $(this).hasClass("clicked") ) {
            $(this).removeClass("clicked");
        } else {
            $(this).addClass("clicked");
        }
    });
    .clicked {
        fill: red !important;  
    }
    
    
    
        
    
    
    
        
            
        
    
    
    

提交回复
热议问题