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

后端 未结 17 1993
死守一世寂寞
死守一世寂寞 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:00

    Here's a version for knockout.js based on the accepted answer:

    Important: It does actually require jQuery too for the replacing, but I thought it may be useful to some.

    ko.bindingHandlers.svgConvert =
        {
            'init': function ()
            {
                return { 'controlsDescendantBindings': true };
            },
    
            'update': function (element, valueAccessor, allBindings, viewModel, bindingContext)
            {
                var $img = $(element);
                var imgID = $img.attr('id');
                var imgClass = $img.attr('class');
                var imgURL = $img.attr('src');
    
                $.get(imgURL, function (data)
                {
                    // Get the SVG tag, ignore the rest
                    var $svg = $(data).find('svg');
    
                    // Add replaced image's ID to the new SVG
                    if (typeof imgID !== 'undefined')
                    {
                        $svg = $svg.attr('id', imgID);
                    }
                    // Add replaced image's classes to the new SVG
                    if (typeof imgClass !== 'undefined')
                    {
                        $svg = $svg.attr('class', imgClass + ' replaced-svg');
                    }
    
                    // Remove any invalid XML tags as per http://validator.w3.org
                    $svg = $svg.removeAttr('xmlns:a');
    
                    // Replace image with new SVG
                    $img.replaceWith($svg);
    
                }, 'xml');
    
            }
        };
    

    Then just apply data-bind="svgConvert: true" to your img tag.

    This solution completely replaces the img tag with a SVG and any additional bindings would not be respected.

提交回复
热议问题