it-source

CSS(jQuery SVG image replacement)를 사용하여 SVG 이미지의 색상을 변경하는 방법은 무엇입니까?

criticalcode 2023. 5. 21. 11:37
반응형

CSS(jQuery SVG image replacement)를 사용하여 SVG 이미지의 색상을 변경하는 방법은 무엇입니까?

이것은 제가 생각해낸 편리한 코드 조각의 자체 질의응답입니다.

현재 SVG 이미지를 내장한 다음 CSS를 통해 SVG 요소에 액세스할 수 있는 쉬운 방법은 없습니다.JS SVG 프레임워크를 사용하는 방법은 다양하지만 롤오버 상태의 간단한 아이콘만 만드는 경우에는 너무 복잡합니다.

제가 생각해낸 것은 이것입니다. 제 생각에는 웹사이트에서 SVG 파일을 사용하는 가장 쉬운 방법입니다.초기 텍스트에서 이미지로 교체하는 방법에서 그 개념을 취하지만, 제가 알기로는 SVG에 대해 수행된 적이 없습니다.

질문은 다음과 같습니다.

JS-SVG 프레임워크를 사용하지 않고 어떻게 SVG를 내장하고 CSS에서 색상을 변경할 수 있습니까?

먼저 HTML에 IMG 태그를 사용하여 SVG 그래픽을 내장합니다.저는 그래픽을 만들기 위해 어도비 일러스트레이터를 사용했습니다.

<img id="facebook-logo" class="svg social-link" src="/images/logo-facebook.svg"/>

이것은 일반적인 이미지를 포함하는 것과 같습니다.IMG의 클래스가 svg가 되도록 설정해야 합니다.'소셜 링크' 수업은 단지 예시를 위한 것입니다.ID는 필수는 아니지만 유용합니다.

그런 다음 이 jQuery 코드(별도 파일 또는 HEAD의 인라인)를 사용합니다.

    /**
     * Replace all SVG images with inline SVG
     */
        jQuery('img.svg').each(function(){
            var $img = jQuery(this);
            var imgID = $img.attr('id');
            var imgClass = $img.attr('class');
            var imgURL = $img.attr('src');

            jQuery.get(imgURL, function(data) {
                // Get the SVG tag, ignore the rest
                var $svg = jQuery(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');

        });

위의 코드는 클래스가 'svg'인 모든 IMG를 찾아 링크된 파일의 인라인 SVG로 대체합니다.큰 장점은 다음과 같이 CSS를 사용하여 SVG의 색을 변경할 수 있다는 것입니다.

svg:hover path {
    fill: red;
}

제가 작성한 jQuery 코드도 원본 이미지 ID와 클래스에 걸쳐 포트를 제공합니다.따라서 이 CSS도 작동합니다.

#facebook-logo:hover path {
    fill: red;
}

또는:

.social-link:hover path {
    fill: red;
}

http://labs.funkhausdesign.com/examples/img-svg/img-to-svg.html 에서 작동하는 예를 볼 수 있습니다.

캐슁이 포함된 더 복잡한 버전이 있습니다. https://github.com/funkhaus/style-guide/blob/master/template/js/site.js#L32-L90

스타일.

svg path {
    fill: #000;
}

대본

$(document).ready(function() {
    $('img[src$=".svg"]').each(function() {
        var $img = jQuery(this);
        var imgURL = $img.attr('src');
        var attributes = $img.prop("attributes");

        $.get(imgURL, function(data) {
            // Get the SVG tag, ignore the rest
            var $svg = jQuery(data).find('svg');

            // Remove any invalid XML tags
            $svg = $svg.removeAttr('xmlns:a');

            // Loop through IMG attributes and apply on SVG
            $.each(attributes, function() {
                $svg.attr(this.name, this.value);
            });

            // Replace IMG with SVG
            $img.replaceWith($svg);
        }, 'xml');
    });
});

이제 대부분의 최신 브라우저(Edge 포함)에서 CSS 속성을 사용할 수 있습니다(IE11은 사용할 수 없음).SVG 영상뿐만 아니라 다른 요소에서도 작동합니다.사용할 수 있습니다.hue-rotate또는invert색을 수정할 수 있지만 다른 색을 개별적으로 수정할 수는 없습니다.다음 CSS 클래스를 사용하여 아이콘의 "비활성화" 버전을 표시합니다(여기서 원본은 포화 색상의 SVG 그림입니다).

.disabled {
    opacity: 0.4;
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
}

이렇게 하면 대부분의 브라우저에서 옅은 회색이 됩니다.IE(그리고 아마도 내가 테스트하지 않은 오페라 미니)에서는 불투명 특성으로 인해 눈에 띄게 희미해졌는데, 회색은 아니지만 여전히 꽤 좋아 보입니다.

여기 Twemoji 벨 아이콘에 대한 네 가지 다른 CSS 클래스가 있는 예가 있습니다: 오리지널(노란색), 위의 "비활성화" 클래스,hue-rotate) 및 (으) 및invert(파란색).

.twa-bell {
  background-image: url("https://twemoji.maxcdn.com/svg/1f514.svg");
  display: inline-block;
  background-repeat: no-repeat;
  background-position: center center;
  height: 3em;
  width: 3em;
  margin: 0 0.15em 0 0.3em;
  vertical-align: -0.3em;
  background-size: 3em 3em;
}
.grey-out {
  opacity: 0.4;
  filter: grayscale(100%);
  -webkit-filter: grayscale(100%);
}
.hue-rotate {
  filter: hue-rotate(90deg);
  -webkit-filter: hue-rotate(90deg);
}
.invert {
  filter: invert(100%);
  -webkit-filter: invert(100%);
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <span class="twa-bell"></span>
  <span class="twa-bell grey-out"></span>
  <span class="twa-bell hue-rotate"></span>
  <span class="twa-bell invert"></span>
</body>

</html>

CSS CSS를 할 수도 .mask허용된 브라우저 지원은 좋지 않지만 폴백을 사용할 수 있습니다.

.frame {
    background: blue;
    -webkit-mask: url(image.svg) center / contain no-repeat;
}

페이지에 파일(PHP가 선택한 CMS를 통해 포함 또는 포함)을 포함할 수 있는 경우 SVG 코드를 추가하여 페이지에 포함할 수 있습니다.이것은 SVG 소스를 페이지에 붙여넣는 것과 동일하게 작동하지만 페이지 마크업을 더 깨끗하게 만듭니다.

이점은 호버를 위해 SVG의 일부를 CSS를 통해 대상으로 지정할 수 있다는 것입니다. 자바스크립트가 필요하지 않습니다.

http://codepen.io/chriscoyier/pen/evcBu

다음과 같은 CSS 규칙을 사용하면 됩니다.

#pathidorclass:hover { fill: #303 !important; }

로 고는 다음과 .!important채우기 색을 재정의하려면 비트가 필요합니다.

TL/DR: 여기로 이동 -> https://codepen.io/sosuke/pen/Pjoqqp

설명:

다음과 같은 html이 있을 거라고 생각합니다.

<img src="/img/source.svg" class="myClass">

필터 경로를 사용하십시오. 즉, svg가 검은색 또는 흰색일 가능성이 높습니다.필터를 적용하여 원하는 색상으로 만들 수 있습니다. 예를 들어, 저는 민트 그린을 원하는 검은색 svg를 가지고 있습니다.저는 먼저 흰색(기술적으로 전체 RGB 색상)으로 반전한 다음 색상 포화도 등을 사용하여 재생합니다.올바른 방법:

filter: invert(86%) sepia(21%) saturate(761%) hue-rotate(92deg) brightness(99%) contrast(107%);

더 좋은 점은 원하는 16진수를 필터로 변환하는 도구를 사용할 수 있다는 것입니다. https://codepen.io/sosuke/pen/Pjoqqp

@드류 베이커는 그 문제를 해결하기 위한 훌륭한 해결책을 제시했습니다.코드가 제대로 작동합니다.그러나 AngularJs를 사용하는 사람들은 jQuery에 많은 의존성을 발견할 수 있습니다.따라서 Angular에 붙여넣는 것이 좋은 생각이라고 생각했습니다.JS 사용자, @Drew Baker의 솔루션을 따르는 코드.

동일한 코드의 AngularJs 방식

Html: html 파일에서 다음 태그를 사용합니다.

<svg-image src="/icons/my.svg" class="any-class-you-wish"></svg-image>

지침: 이는 태그를 인식해야 하는 지침입니다.

'use strict';
angular.module('myApp')
  .directive('svgImage', ['$http', function($http) {
    return {
      restrict: 'E',
      link: function(scope, element) {
        var imgURL = element.attr('src');
        // if you want to use ng-include, then
        // instead of the above line write the bellow:
        // var imgURL = element.attr('ng-include');
        var request = $http.get(
          imgURL,
          {'Content-Type': 'application/xml'}
        );

        scope.manipulateImgNode = function(data, elem){
          var $svg = angular.element(data)[4];
          var imgClass = elem.attr('class');
          if(typeof(imgClass) !== 'undefined') {
            var classes = imgClass.split(' ');
            for(var i = 0; i < classes.length; ++i){
              $svg.classList.add(classes[i]);
            }
          }
          $svg.removeAttribute('xmlns:a');
          return $svg;
        };

        request.success(function(data){
          element.replaceWith(scope.manipulateImgNode(data, element));
        });
      }
    };
  }]);

CSS:

.any-class-you-wish{
    border: 1px solid red;
    height: 300px;
    width:  120px
}

카르마 재스민을 사용한 유닛 테스트:

'use strict';

describe('Directive: svgImage', function() {

  var $rootScope, $compile, element, scope, $httpBackend, apiUrl, data;

  beforeEach(function() {
    module('myApp');

    inject(function($injector) {
      $rootScope = $injector.get('$rootScope');
      $compile = $injector.get('$compile');
      $httpBackend = $injector.get('$httpBackend');
      apiUrl = $injector.get('apiUrl');
    });

    scope = $rootScope.$new();
    element = angular.element('<svg-image src="/icons/icon-man.svg" class="svg"></svg-image>');
    element = $compile(element)(scope);

    spyOn(scope, 'manipulateImgNode').andCallThrough();
    $httpBackend.whenGET(apiUrl + 'me').respond(200, {});

    data = '<?xml version="1.0" encoding="utf-8"?>' +
      '<!-- Generator: Adobe Illustrator 17.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->' +
      '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
      '<!-- Obj -->' +
      '<!-- Obj -->' +
      '<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"' +
      'width="64px" height="64px" viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve">' +
        '<g>' +
          '<path fill="#F4A902" d=""/>' +
          '<path fill="#F4A902" d=""/>' +
        '</g>' +
      '</svg>';
    $httpBackend.expectGET('/icons/icon-man.svg').respond(200, data);
  });

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it('should call manipulateImgNode atleast once', function () {
    $httpBackend.flush();
    expect(scope.manipulateImgNode.callCount).toBe(1);
  });

  it('should return correct result', function () {
    $httpBackend.flush();
    var result = scope.manipulateImgNode(data, element);
    expect(result).toBeDefined();
  });

  it('should define classes', function () {
    $httpBackend.flush();
    var result = scope.manipulateImgNode(data, element);
    var classList = ["svg"];
    expect(result.classList[0]).toBe(classList[0]);
  });
});

CSS를 사용하여 이 작업을 수행하고자 하는 것은 알지만, 작고 단순한 이미지일 경우에 대비하여 메모장++에서 언제든지 열고 경로/요소 채우기를 변경할 수 있습니다.

<path style="fill:#010002;" d="M394.854,205.444c9.218-15.461,19.102-30.181,14.258-49.527
    ...
    C412.843,226.163,402.511,211.451,394.854,205.444z"/>

그것은 엄청난 양의 추악한 대본을 절약할 수 있습니다.기본이 아닌 경우에는 죄송합니다. 하지만 때때로 간단한 해결책을 간과할 수 있습니다.

...여러 svg 이미지를 스왑하더라도 이 질문에 대한 일부 코드 스니펫보다 크기가 작을 수 있습니다.

저는 AngularJS로 이 문제를 해결하기 위해 지침서를 작성했습니다.ngReuseableSvg는 여기에서 사용할 수 있습니다.

후 요소대내배다치니합부고 합니다.div요소, CSS를 쉽게 변경할 수 있도록 합니다.이렇게 하면 크기/색상이 다른 여러 위치에서 동일한 SVG 파일을 사용할 수 있습니다.

사용 방법은 간단합니다.

<object oa-reusable-svg
        data="my_icon.svg"
        type="image/svg+xml"
        class="svg-class"
        height="30"  // given to prevent UI glitches at switch time
        width="30">
</object>

그 후에는 다음과 같은 기능을 쉽게 사용할 수 있습니다.

.svg-class svg {
    fill: red; // whichever color you want
}

▁version다니▁의 버전이 있습니다.knockout.js승인된 답변을 기준으로 합니다.

중요:실제로 교체를 위해서도 jQuery가 필요하지만, 일부에게는 유용할 것이라고 생각했습니다.

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');

        }
    };

그럼 그냥 신청하세요.data-bind="svgConvert: true"당신의 img 태그에.

이 솔루션은 다음과 같은 솔루션을 완전히 대체합니다.imgSVG로 태그를 지정하고 추가 바인딩은 허용되지 않습니다.

, 이 는 SVInject라는 이름으로 됩니다.onload주입을 트리거하는 속성입니다.깃허브 프로젝트는 https://github.com/iconfu/svg-inject 에서 찾을 수 있습니다.

다음은 SVGInject를 사용하는 최소한의 예입니다.

<html>
  <head>
    <script src="svg-inject.min.js"></script>
  </head>
  <body>
    <img src="image.svg" onload="SVGInject(this)" />
  </body>
</html>

에는 이지가 onload="SVGInject(this)와 주을트하고거리입을 .<img>는 SVG 파일에 됩니다.src기여하다.

SVG 주입을 통해 다음과 같은 몇 가지 문제를 해결합니다.

  1. 주입이 완료될 때까지 SVG를 숨길 수 있습니다.로드 시간 중에 스타일이 이미 적용된 경우, 그렇지 않으면 "스타일링되지 않은 콘텐츠 플래시"가 잠깐 발생할 수 있으므로 이 점이 중요합니다.

  2. <img>요소가 자동으로 주입됩니다.SVG를 동적으로 추가하면 주입 기능을 다시 호출할 걱정이 없습니다.

  3. SVG가 두 번 이상 주입되는 경우 문서에서 동일한 ID를 여러 번 갖지 않도록 SVG의 각 ID에 임의 문자열이 추가됩니다.

SVGInject는 일반 Javascript이며 SVG를 지원하는 모든 브라우저에서 작동합니다.

고지 사항:저는 SVGInject의 공동 저자입니다.

다음은 프레임워크 코드가 없고 순수한 js만 있습니다.

document.querySelectorAll('img.svg').forEach(function(element) {
            var imgID = element.getAttribute('id')
            var imgClass = element.getAttribute('class')
            var imgURL = element.getAttribute('src')

            xhr = new XMLHttpRequest()
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && xhr.status == 200) {
                    var svg = xhr.responseXML.getElementsByTagName('svg')[0];

                    if(imgID != null) {
                         svg.setAttribute('id', imgID);
                    }

                    if(imgClass != null) {
                         svg.setAttribute('class', imgClass + ' replaced-svg');
                    }

                    svg.removeAttribute('xmlns:a')

                    if(!svg.hasAttribute('viewBox') && svg.hasAttribute('height') && svg.hasAttribute('width')) {
                        svg.setAttribute('viewBox', '0 0 ' + svg.getAttribute('height') + ' ' + svg.getAttribute('width'))
                    }
                    element.parentElement.replaceChild(svg, element)
                }
            }
            xhr.open('GET', imgURL, true)
            xhr.send(null)
        })

이러한 svg 이미지가 더 많으면 글꼴 파일의 도움도 받을 수 있습니다.
https://glyphter.com/ 같은 사이트에서 svgs에서 글꼴 파일을 얻을 수 있습니다.


예.

@font-face {
    font-family: 'iconFont';
    src: url('iconFont.eot');
}
#target{
    color: white;
    font-size:96px;
    font-family:iconFont;
}

데이터 이미지를 사용할 수 있습니다.데이터 이미지(data-URI)를 사용하면 SVG에 인라인처럼 액세스할 수 있습니다.

순수 CSS와 SVG를 사용한 롤오버 효과입니다.

지저분하다는 건 알지만 이런 식으로 하시면 됩니다.

 .action-btn {
    background-size: 20px 20px;
    background-position: center center;
    background-repeat: no-repeat;
    border-width: 1px;
    border-style: solid;
    border-radius: 30px;
    height: 40px;
    width: 60px;
    display: inline-block;
 }

.delete {
     background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg version='1.1' id='Capa_1' fill='#FB404B' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='482.428px' height='482.429px' viewBox='0 0 482.428 482.429' style='enable-background:new 0 0 482.428 482.429;' xml:space='preserve'%3e%3cg%3e%3cg%3e%3cpath d='M381.163,57.799h-75.094C302.323,25.316,274.686,0,241.214,0c-33.471,0-61.104,25.315-64.85,57.799h-75.098 c-30.39,0-55.111,24.728-55.111,55.117v2.828c0,23.223,14.46,43.1,34.83,51.199v260.369c0,30.39,24.724,55.117,55.112,55.117 h210.236c30.389,0,55.111-24.729,55.111-55.117V166.944c20.369-8.1,34.83-27.977,34.83-51.199v-2.828 C436.274,82.527,411.551,57.799,381.163,57.799z M241.214,26.139c19.037,0,34.927,13.645,38.443,31.66h-76.879 C206.293,39.783,222.184,26.139,241.214,26.139z M375.305,427.312c0,15.978-13,28.979-28.973,28.979H136.096 c-15.973,0-28.973-13.002-28.973-28.979V170.861h268.182V427.312z M410.135,115.744c0,15.978-13,28.979-28.973,28.979H101.266 c-15.973,0-28.973-13.001-28.973-28.979v-2.828c0-15.978,13-28.979,28.973-28.979h279.897c15.973,0,28.973,13.001,28.973,28.979 V115.744z'/%3e%3cpath d='M171.144,422.863c7.218,0,13.069-5.853,13.069-13.068V262.641c0-7.216-5.852-13.07-13.069-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C158.074,417.012,163.926,422.863,171.144,422.863z'/%3e%3cpath d='M241.214,422.863c7.218,0,13.07-5.853,13.07-13.068V262.641c0-7.216-5.854-13.07-13.07-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C228.145,417.012,233.996,422.863,241.214,422.863z'/%3e%3cpath d='M311.284,422.863c7.217,0,13.068-5.853,13.068-13.068V262.641c0-7.216-5.852-13.07-13.068-13.07 c-7.219,0-13.07,5.854-13.07,13.07v147.154C298.213,417.012,304.067,422.863,311.284,422.863z'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e ");
     border-color:#FB404B;
     
 }
 
 .delete:hover {
     background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg version='1.1' id='Capa_1' fill='#fff' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='482.428px' height='482.429px' viewBox='0 0 482.428 482.429' style='enable-background:new 0 0 482.428 482.429;' xml:space='preserve'%3e%3cg%3e%3cg%3e%3cpath d='M381.163,57.799h-75.094C302.323,25.316,274.686,0,241.214,0c-33.471,0-61.104,25.315-64.85,57.799h-75.098 c-30.39,0-55.111,24.728-55.111,55.117v2.828c0,23.223,14.46,43.1,34.83,51.199v260.369c0,30.39,24.724,55.117,55.112,55.117 h210.236c30.389,0,55.111-24.729,55.111-55.117V166.944c20.369-8.1,34.83-27.977,34.83-51.199v-2.828 C436.274,82.527,411.551,57.799,381.163,57.799z M241.214,26.139c19.037,0,34.927,13.645,38.443,31.66h-76.879 C206.293,39.783,222.184,26.139,241.214,26.139z M375.305,427.312c0,15.978-13,28.979-28.973,28.979H136.096 c-15.973,0-28.973-13.002-28.973-28.979V170.861h268.182V427.312z M410.135,115.744c0,15.978-13,28.979-28.973,28.979H101.266 c-15.973,0-28.973-13.001-28.973-28.979v-2.828c0-15.978,13-28.979,28.973-28.979h279.897c15.973,0,28.973,13.001,28.973,28.979 V115.744z'/%3e%3cpath d='M171.144,422.863c7.218,0,13.069-5.853,13.069-13.068V262.641c0-7.216-5.852-13.07-13.069-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C158.074,417.012,163.926,422.863,171.144,422.863z'/%3e%3cpath d='M241.214,422.863c7.218,0,13.07-5.853,13.07-13.068V262.641c0-7.216-5.854-13.07-13.07-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C228.145,417.012,233.996,422.863,241.214,422.863z'/%3e%3cpath d='M311.284,422.863c7.217,0,13.068-5.853,13.068-13.068V262.641c0-7.216-5.852-13.07-13.068-13.07 c-7.219,0-13.07,5.854-13.07,13.07v147.154C298.213,417.012,304.067,422.863,311.284,422.863z'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e ");        
     background-color: #FB404B;
    }
<a class="action-btn delete">&nbsp;</a>

여기에서 svg를 데이터 url로 변환할 수 있습니다.

  1. https://codepen.io/elliz/full/ygvgay
  2. https://websemantics.uk/tools/svg-to-background-image-conversion/

SVG는 기본적으로 코드이기 때문에 콘텐츠만 있으면 됩니다.저는 PHP를 사용하여 콘텐츠를 얻었지만, 당신은 원하는 것을 사용할 수 있습니다.

<?php
$content    = file_get_contents($pathToSVG);
?>

그런 다음, div 컨테이너 안에 있는 내용을 "있는 그대로" 인쇄했습니다.

<div class="fill-class"><?php echo $content;?></div>

CSS에서 컨테이너의 SVG 자식에 대한 규칙을 최종적으로 설정하려면 다음과 같이 하십시오.

.fill-class > svg { 
    fill: orange;
}

재료 아이콘 SVG를 사용하여 다음과 같은 결과를 얻었습니다.

  1. Mozilla Firefox 59.0.2(64비트) Linux

여기에 이미지 설명 입력

  1. Google Chrome 66.0.3359.181 (빌드 공식) (64비트) Linux

여기에 이미지 설명 입력

  1. 오페라 53.0.2907.37 리눅스

여기에 이미지 설명 입력

JQuery에서 DOM의 모든 svg 요소를 처리하고 DOM의 크기가 적절한 경우 선택한 솔루션이 좋습니다.그러나 DOM이 크고 DOM의 일부를 동적으로 로드하기로 결정한 경우 svg 요소를 업데이트하기 위해 전체 DOM을 다시 검색해야 하는 것은 정말 말이 되지 않습니다.대신 jQuery 플러그인을 사용하여 다음 작업을 수행합니다.

/**
 * 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 <svg> 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 = $('<a></a>').append(svg.clone()).html();
            ctx.replaceWith(newHtml);
        });

        return this;
    };

}(jQuery));

html에서 다음과 같이 svg 요소를 지정합니다.

<svg src="images/someSvgFile.svg" height="45" width="45" class="mySVGClass"/>

플러그인을 적용합니다.

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

: 이벤트 애니메이션을 보여주는 것처럼 svg 파일 안에 스타일을 남길 수 있습니다.

<svg xmlns="http://www.w3.org/2000/svg">
<defs>
  <style>
  rect {
    fill:rgb(165,225,75);
    stroke:none;
    transition: 550ms ease-in-out;
    transform-origin:125px 125px;
  }
  rect:hover {
    fill:rgb(75,165,225);
    transform:rotate(360deg);
  }
  </style>
</defs>
  <rect x='50' y='50' width='150' height='150'/>
</svg>

svgshare에서 이것을 확인합니다.

.carousel-control-prev-icon {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='rgb(3,122,247)' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e");
}

chnage color : fill='fill(3,122,247)'

언급URL : https://stackoverflow.com/questions/11978995/how-to-change-color-of-svg-image-using-css-jquery-svg-image-replacement

반응형