代码之家  ›  专栏  ›  技术社区  ›  Randy Hall

在维护CSS控件的同时重用SVG图像

  •  0
  • Randy Hall  · 技术社区  · 6 年前

    我有一些剪影类型的图像,他们需要能够改变颜色,有时只是显示在不同的位置,有时是悬停效果。

    这对于直接嵌入到HTML中的SVG来说非常简单。复制粘贴和CSS到你的心的愿望。

    但是我必须复制粘贴或程序插入到我想要的任何地方。其中一些被使用了几十次。重复传输同一个SVG标记的做法似乎很糟糕。

    是否有一个两全其美的解决方案,在那里我可以CSS路径,也可以在前端以某种方式重用SVG?

    1 回复  |  直到 6 年前
        1
  •  1
  •   ippi    6 年前

    <svg style="display: none;">
      <symbol id="ic">
          <paths and polygons and other fun stuff>
      </symbol>
    </svg>
    

    <use> xlink:href 指向您制作的符号。你可以自由地添加类来改变事情:

    <svg viewBox="0 0 100 125" xmlns:xlink="http://www.w3.org/1999/xlink">
      <use xlink:href="#ic" class="ic-blue"  x="0" y="0" />
    </svg>
    

    https://tympanus.net/codrops 去阅读他们的内容,然后点击他们的广告!如果有一个网站值得你的广告屏蔽例外,这就是它。

    https://tympanus.net/codrops/2015/07/16/styling-svg-use-content-css/

    body {
      padding: 2em;
    }
    svg {
      width: 100px;
      height: 125px;
      border: 1px solid #ddd;
    }
    use.ic-1 {
      fill: skyblue;
    }
    use.ic-2 {
      fill: #FDC646;
    }
    use.ic-3 {
      fill: #FF2D49;
    }
    
    svg path {
      fill: inherit;
    }
    <svg style="display: none;">
      <symbol id="ic">
        <path fill="#000000" d="M81,40.933c0-4.25-3-7.811-6.996-8.673c-0.922-5.312-3.588-10.178-7.623-13.844  c-2.459-2.239-5.326-3.913-8.408-4.981c-0.797-3.676-4.066-6.437-7.979-6.437c-3.908,0-7.184,2.764-7.979,6.442  c-3.078,1.065-5.939,2.741-8.396,4.977c-4.035,3.666-6.701,8.531-7.623,13.844C22.002,33.123,19,36.682,19,40.933  c0,2.617,1.145,4.965,2.957,6.589c0.047,0.195,0.119,0.389,0.225,0.568l26.004,43.873c0.383,0.646,1.072,1.04,1.824,1.04  c0.748,0,1.439-0.395,1.824-1.04L77.82,48.089c0.105-0.179,0.178-0.373,0.225-0.568C79.855,45.897,81,43.549,81,40.933z   M49.994,11.235c2.164,0,3.928,1.762,3.928,3.93c0,2.165-1.764,3.929-3.928,3.929s-3.928-1.764-3.928-3.929  C46.066,12.997,47.83,11.235,49.994,11.235z M27.842,36.301c0.014,0,0.027,0,0.031,0c1.086,0,1.998-0.817,2.115-1.907  c0.762-7.592,5.641-13.791,12.303-16.535c1.119,3.184,4.146,5.475,7.703,5.475c3.561,0,6.588-2.293,7.707-5.48  c6.664,2.742,11.547,8.944,12.312,16.54c0.115,1.092,1.037,1.929,2.143,1.907c2.541,0.013,4.604,2.087,4.604,4.631  c0,1.684-0.914,3.148-2.266,3.958H25.508c-1.354-0.809-2.268-2.273-2.268-3.958C23.24,38.389,25.303,36.316,27.842,36.301z   M50.01,86.723L27.73,49.13h44.541L50.01,86.723z"/>
      </symbol>
    </svg>
    <svg viewBox="0 0 100 125" xmlns:xlink="http://www.w3.org/1999/xlink">
      <use class="ic-1" xlink:href="#ic" x="0" y="0" />
    </svg>
    <svg viewBox="0 0 100 125" xmlns:xlink="http://www.w3.org/1999/xlink">
      <use class="ic-2" xlink:href="#ic" x="0" y="0" />
    </svg>
    <svg viewBox="0 0 100 125" xmlns:xlink="http://www.w3.org/1999/xlink">
      <use class="ic-3" xlink:href="#ic" x="0" y="0" />
    </svg>