How to change SVG's path color?

前端 未结 3 1813
生来不讨喜
生来不讨喜 2021-01-12 19:11

Update: Yes, I know there are similar questions on SO, but the solutions don\'t work either.

I want to change SVG\'s color, I mean paths\'s color, n

3条回答
  •  天命终不由人
    2021-01-12 19:29

    Base on accepted answer, I created sample to click button and change color path.

    Important thing:

    I need host HTML file to webserver (IIS) to run it. If not it a.contentDocument always return null.

    I share for whom concerned.

            var svgDoc;
            function changeColor() {
                svgDoc = a.contentDocument;
                // get the inner element by id
                var paths = svgDoc.querySelectorAll("path");
                // add behaviour
                for (i = 0; i < paths.length; i++) {
                    paths[i].setAttribute('style', 'fill:pink');
                }
            }
    
            var a = document.getElementById("alphasvg");
    
            // It's important to add an load event listener to the object,
            // as it will load the svg doc asynchronously
            a.addEventListener("load", function () {
    
                // get the inner DOM of alpha.svg
                svgDoc = a.contentDocument;
                // get the inner element by id
                var paths = svgDoc.querySelectorAll("path");
                // add behaviour
                for (i = 0; i < paths.length; i++) {
                    paths[i].setAttribute('style', 'fill:green');
                }
    
            }, false);
    
    
    
    
        
        
        Document
    
    
    
        
        
    
        
    
        
    
    
    

提交回复
热议问题