如何在SVG中继承描边颜色?(不是填充,而是描边颜色)

7

我有一个 .SVG 文件,用 <img src="/image/arrow.svg" alt="箭头"> 进行调用。一切都很好,但我希望能够动态地为我的 SVG 设置不同的描边颜色(而不是填充颜色...) ,例如 <img ... style="color:red">。我读到可以在我的路径上使用 fill="currentColor",但如何为我的描边颜色做到这一点呢?

我的 SVG 文件:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="100" width="100">
    <path d="M20 10 H90 V80" fill="transparent" stroke="currentColor" stroke-width="20" stroke-linecap="round"></path>
    <path d="M10 90 L100 0" fill="transparent" stroke="currentColor" stroke-width="20" stroke-linecap="round"></path>
</svg>

我的 HTML:

<img src="/image/arrow.svg" alt="Arrow" style="color:red">

3
图片无法从宿主文档继承任何内容。您可以将标记内联放置。 - Robert Longson
1个回答

7
Robert Longson 正确指出的,并且之前在StackOverflow上也有讨论过,SVG被用作图像元素时有一个新的图像上下文,因此它不使用文档的样式,而内联SVG元素则使用它们。
因此,以下示例有效:

svg.red {
  color: red;
}
<svg class="red" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="100" width="100">
    <path d="M20 10 H90 V80" fill="transparent" stroke="currentColor" stroke-width="20" stroke-linecap="round"></path>
    <path d="M10 90 L100 0" fill="transparent" stroke="currentColor" stroke-width="20" stroke-linecap="round"></path>
</svg>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接