gpt4 book ai didi

javascript - 使用 CSS 控制 SVG 颜色

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:00 25 4
gpt4 key购买 nike

我正在使用一些基本 CSS 和 SVG Sprite(通过 webpack 生成)的库中设置一些图标。

一些图标我希望能够用多种颜色着色。我的设置如下:

ma​​il.svg (为简单起见省略了 svg 的详细信息)

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 64 64" width="64" height="64">
<polyline class="primary-stroke" fill="none" stroke-width="2" [more-stuff-here]></polyline>
<path fill="none" stroke-width="2" [more-stuff-here]></path>
<line class="primary-stroke" fill="none" stroke-width="2" [more-stuff-here]></line>
</svg>

我计算的 CSS(blue 是主要强调色)看起来像:

svg {
fill: currentColor;
stroke: currentColor;
}

.primary-stroke {
stroke: blue;
fill: none;
}

我的 HTML 看起来像:

<svg><use xlink:href="#mail"></svg>

这一切都按预期工作,但现在我想更进一步。我希望能够向该元素添加一个类以确定 实例是否应包含 1 种单一颜色或 2 种颜色。

我的尝试非常简单。我刚刚向 svg 元素添加了一个 single-color 类,看起来像:

<svg class="single-color"><use xlink:href="#mail"></svg>

并修改了SCSS。计算出的 CSS 如下所示:

.single-color .primary-stroke {
stroke: currentColor;
fill: none;
}

但是,这绝对行不通。 primary 样式仍然有效。我是 SVG 的新手,我不确定我尝试做的事情是否可以用 sprite 实现?

演示问题的 CodePens:

两个示例都使用相同的类和 SVG。

最佳答案

<use> 引用的元素元素本身不是 DOM 链的一部分,它只存在于影子 DOM 中,因此,您无法通过选择器访问它。

解决方案是直接定位 <use>元素本身,并且不要为内部 .primary-stroke 设置规则这样他们就可以继承自 <use> .

/* 
don't set any direct rule on the .variable ones
otherwise, they won't be able to inherit from the <use>
*/

/* target the uses */
.stroke-only use[href="#rects"] {
stroke: blue;
fill: none;
}
.stroke-and-fill use[href="#rects"] {
stroke: blue;
fill: green;
}

/* this one won't get influenced by the <use> */
.fixed {
fill: orange;
stroke: red;
}

svg { display: block; }
<svg width="0" height="0" style="position:absolute;z-index:-1">
<defs>
<g id="rects">
<rect class="variable" x=5 y=5 width=50 height=50 />
<rect class="fixed" x=60 y=5 width=50 height=50 />
</g>
</defs>
</svg>

<svg class="stroke-only" height=70 >
<use href=#rects />
</svg>

<svg class="stroke-and-fill" height=70 >
<use href=#rects />
</svg>


然后对于代码笔中的示例,您需要为不改变颜色的一条路径添加特定规则,例如:

#mail path:not([class]) {
stroke: currentColor;
fill: none;
}

updated codepen .

但如果您可以控制此 sprite-sheet,最好是用一个类来标记它(就像我用 .fixed 所做的那样)。

关于javascript - 使用 CSS 控制 SVG 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com