How to change color of SVG image using CSS (jQuery SVG image replacement)?

后端 未结 17 1989
死守一世寂寞
死守一世寂寞 2020-11-21 17:36

This is a self Q&A of a handy piece of code I came up with.

Currently, there isn\'t an easy way to embed an SVG image and then have access to the SVG elements vi

17条回答
  •  臣服心动
    2020-11-21 18:03

    The selected solution is fine if you want jQuery to process all svg elements in your DOM and your DOM is of reasonable size. But if your DOM is large and you decide to load parts of your DOM dynamically, it really makes no sense to have to rescan the entire DOM just to update svg elements. Instead, use a jQuery plugin to do this:

    /**
     * A jQuery plugin that loads an svg file and replaces the jQuery object with its contents.
     *
     * The path to the svg file is specified in the src attribute (which normally does not exist for an svg element).
     *
     * The width, height and class attributes in the loaded svg will be replaced by those that exist in the jQuery object's
     * underlying html. Note: All other attributes in the original element are lost including the style attribute. Place
     * any styles in a style class instead.
     */
    (function ($) {
        $.fn.svgLoader = function () {
            var src = $(this).attr("src");
            var width = this.attr("width");
            var height = this.attr("height");
            var cls = this.attr("class");
            var ctx = $(this);
    
            // Get the svg file and replace the  element.
            $.ajax({
                url: src,
                cache: false
            }).done(function (html) {
                let svg = $(html);
                svg.attr("width", width);
                svg.attr("height", height);
                svg.attr("class", cls);
                var newHtml = $('').append(svg.clone()).html();
                ctx.replaceWith(newHtml);
            });
    
            return this;
        };
    
    }(jQuery));
    

    In your html, specify an svg element as follows:

    
    

    And apply the plugin:

    $(".mySVGClass").svgLoader();
    

提交回复
热议问题