【问题标题】:Adding drop shadows to SVG symbols为 SVG 符号添加阴影
【发布时间】:2016-07-19 15:34:30
【问题描述】:

我正在构建一个使用大量图标的网站,因此我正在使用 SVG 符号来减少重复。在某些情况下,设计要求符号具有阴影,而在其他情况下则不需要。我正在努力弄清楚如何添加阴影。

我的 SVG 示例:

<svg id="icons-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
...
<symbol id="icon-communications" viewBox="1400 0 200 200">
    <title>Communications</title>
    <rect style="fill: currentColor" x="1447.3" y="95.3" width="105.3" height="5.3"/>
    <rect style="fill: currentColor" x="1447.3" y="78" width="105.3" height="5.3"/>
    <polygon style="fill: currentColor" points="1463.2,127.9 1468,130.1 1475.7,113.6 1470.9,111.4   "/>
    ...
</symbol>
...
</svg>

然后我使用标准在页面上包含图标:

<svg class="icon-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <use xlink:href="#icon-communications"/>
</svg>

然后我可以像这样设置图标的颜色:

.icon-svg use {
    color: blue;
}
.error .icon-svg use {
    color: red;
}

但我不知道如何添加投影。我尝试过 CSS box-shadow,也尝试过 filter: drop-shadow(),但似乎都没有做任何事情。例如

.someClass .icon-svg use {
    color: #fff;
    -webkit-filter: drop-shadow( 0 0 20px #000 );
    filter: drop-shadow( 0 0 20px #000 );
}

任何帮助将不胜感激。

【问题讨论】:

  • 是的...我不认为你可以用 &lt;use&gt; 只使用内联 SVG 来做到这一点。 - stackoverflow.com/questions/6088409/…
  • 或者是否可以将其包含在 SVG 中并使用 CSS 将其关闭,或者是否具有完全相同的限制?
  • 我认为它会有同样的问题。我只是从我的阅读中假设。到达进入 &lt;use&gt; 并将CSS 应用到(有效地)*parts' 是很困难的,如果不是不可能的话。我会等待一些 SVG 专家的出现。如果@RobertLongson cmets..把它当作福音。
  • 我的经验是 SVG 渲染正常,没有令人反感的时间延迟,有多达 5000 个单独的克隆而不是元素的 。它允许更多地访问元素的动态自定义。
  • 我有一个解决方案,但在 IE 中不起作用。如果我修改原始符号 SVG 上的样式属性以包含 'filter:var(--filter-name)' 我可以在我的 CSS 中设置引用 SVG 过滤器的过滤器名称,例如'--filter-name: url(#dropshadow);'.

标签: html css svg shadow


【解决方案1】:

使用 SVG 滤镜:

.icon-svg use {
    color: blue;
}
.error .icon-svg use {
    color: red;
}

.icon-svg {
  -webkit-filter: url(#dropshadowy);
}
<svg id="icons-svg" >
  <defs>
<filter id="dropshadowy">
  <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
  <feMerge>
    <feMergeNode/>
    <feMergeNode in="SourceGraphic"/>
  </feMerge>
</filter>
    
<symbol id="icon-communications" viewBox="1400 0 200 200">
    <title>Communications</title>

    <rect style="fill: currentColor" x="1447.3" y="95.3" width="105.3" height="5.3"/>
    <rect style="fill: currentColor" x="1447.3" y="78" width="105.3" height="5.3"/>
    <polygon style="fill: currentColor" points="1463.2,127.9 1468,130.1 1475.7,113.6 1470.9,111.4   "/>

</symbol>
  </defs>

</svg>


<svg class="icon-svg" >
 
    <use xlink:href="#icon-communications"/>

</svg>

【讨论】:

  • 在 FF 47.0.1 或 Edge 14.14393 中对我不起作用。是的,在 Chrome 中。我无法弄清楚为什么您的原始代码不起作用 - 我在我的网站 [potoococha.net/][1] 上做了同样的事情,它适用于所有浏览器。我建议关闭所有标签、使用、矩形和多边形可能不是“自动关闭”。而且你不应该需要在你的css中使用 use 元素名称——只需要类名就足够了。 [1]:potoococha.net
  • 是的,我没有写跨浏览器的 polyfills
猜你喜欢
  • 2015-01-19
  • 2021-03-23
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
相关资源
最近更新 更多