img src SVG changing the styles with CSS

后端 未结 22 1999
予麋鹿
予麋鹿 2020-11-22 01:16

html

\"Logo\"

css

.logo-img path {
           


        
22条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:59

    This answer is based on answer https://stackoverflow.com/a/24933495/3890888 but with a plain JavaScript version of the script used there.

    You need to make the SVG to be an inline SVG. You can make use of this script, by adding a class svg to the image:

    /*
     * Replace all SVG images with inline SVG
     */
    document.querySelectorAll('img.svg').forEach(function(img){
        var imgID = img.id;
        var imgClass = img.className;
        var imgURL = img.src;
    
        fetch(imgURL).then(function(response) {
            return response.text();
        }).then(function(text){
    
            var parser = new DOMParser();
            var xmlDoc = parser.parseFromString(text, "text/xml");
    
            // Get the SVG tag, ignore the rest
            var svg = xmlDoc.getElementsByTagName('svg')[0];
    
            // Add replaced image's ID to the new SVG
            if(typeof imgID !== 'undefined') {
                svg.setAttribute('id', imgID);
            }
            // Add replaced image's classes to the new SVG
            if(typeof imgClass !== 'undefined') {
                svg.setAttribute('class', imgClass+' replaced-svg');
            }
    
            // Remove any invalid XML tags as per http://validator.w3.org
            svg.removeAttribute('xmlns:a');
    
            // Check if the viewport is set, if the viewport is not set the SVG wont't scale.
            if(!svg.getAttribute('viewBox') && svg.getAttribute('height') && svg.getAttribute('width')) {
                svg.setAttribute('viewBox', '0 0 ' + svg.getAttribute('height') + ' ' + svg.getAttribute('width'))
            }
    
            // Replace image with new SVG
            img.parentNode.replaceChild(svg, img);
    
        });
    
    });
    

    And then, now if you do:

    .logo-img path {
      fill: #000;
    }
    

    Or may be:

    .logo-img path {
      background-color: #000;
    }
    

    JSFiddle: http://jsfiddle.net/erxu0dzz/1/

提交回复
热议问题