我正在使用 SVG 构建一个图标解决方案,其中部分图标需要可重用。有几个不同的<svg />
我的 HTML 文档中内联的元素,以及 <use />
element 非常适合重用形状——矩形、路径等,甚至在 svg 元素之间也是如此。
但是,重用其他定义,例如 <radialGradient />
对我不起作用。当梯度定义在<defs />
内时相同的元素<svg />
元素,它按预期工作,但当渐变在另一个 <svg />
中定义时则不然元素。
伪代码
<!-- Near the top of my BODY element -->
<!-- This is where I keep the SVG stuff I want to reuse -->
<svg id="for-reuse" style="display:none">
<defs>
<path id="marker" d="M63 127L49 93C44 80 52 69 63 69L64 69C75 69 83 80 78 93L64 127" />
<radialGradient id="shadow">
<stop offset="10%" stop-color="rgba(0,0,0,0.4)" />
<stop offset="90%" stop-color="rgba(0,0,0,0)" />
</radialGradient>
</defs>
</svg>
<!-- Further down the html document -->
<svg viewBox="0 0 128 128" style="width:64px; height:64px" xmlns="http://www.w3.org/2000/svg" version="1.1">
<!-- This use element works fine! -->
<use xlink:href="#marker" style="fill:black" />
<!-- But this fill attribute does not! -->
<rect x="5" y="5" width="20" height="20" fill="url(#shadow)" />
</svg>
为什么可以use
其他形状svg
元素,但不是这样的属性值?当我移动shadow
时渐变成defs
元素位于可见的 svg 元素内,该引用工作完美。
这是一个 JSFiddle,它说明了工作和非工作: https://jsfiddle.net/7tfna0L8/2/
解决方案
Robert Longson指出我的可重用 svg 的“存储库”有一个 style
的display:none
。对我来说,这感觉是正确的方法。毕竟,这个存储库不应该以任何方式显示。问题是浏览器通过可能根本不解析任何样式来对此进行优化,这使得可以引用元素,但不能引用样式(就像我的渐变)
工作中的 jsFiddle: https://jsfiddle.net/atornblad/7tfna0L8/3/
最佳答案
您的远梯度位于 svg 中,其样式为 display:none。这会禁用该片段中的所有 CSS,因此它不起作用。尝试 width="0"height="0"而不是 display:none。
关于html - 如何从不同的内联 SVG 元素引用 RadialGradient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798890/