我想在网页上放置一些简单的 SVG 图表,并且让 SVG 内容采用周围文本的背景和描边颜色 - 无需依赖某种硬编码的网站构建技术一切。如果用户有个人 CSS 覆盖,或暗模式插件,或其他什么,我想选择并使用它。
在理想的世界中,如果我不指定,那么这应该会自动发生,但事实并非如此。 SVG 的描边颜色可以使用
stroke
设置,但这不会采用纯文本的 color
值。
到目前为止,我想出的只是一些 javascript 来复制值:
function fixSVGStroke() {
for (img of document.getElementsByTagName("svg")) {
style = getComputedStyle(img);
img.style.stroke = style.color;
// img.style.background = style.background; // doesn't work?
}
}
svg { stroke-width:2; fill-opacity:0.35; }
@media (prefers-color-scheme: light) { svg { stroke:black; } }
@media (prefers-color-scheme: dark) { svg { stroke:white; } }
</svg>
<button onclick="fixSVGStroke()">Fix me!</button>
<div>
sample text
<svg width="180" height="40" id="testpattern">
<circle cx="20" cy="20" r="15" fill="grey"/>
<circle cx="60" cy="20" r="15" fill="red"/>
<circle cx="100" cy="20" r="15" fill="green"/>
<circle cx="140" cy="20" r="15" fill="blue"/>
</svg>
(default colours)
</div>
<div style="color:yellow; background:navy">
sample text
<svg width="180" height="40">
<circle cx="20" cy="20" r="15" fill="grey"/>
<circle cx="60" cy="20" r="15" fill="red"/>
<circle cx="100" cy="20" r="15" fill="green"/>
<circle cx="140" cy="20" r="15" fill="blue"/>
</svg>
(yellow/navy)
</div>
<div style="color:maroon; background:silver">
sample text
<svg width="180" height="40">
<circle cx="20" cy="20" r="15" fill="grey"/>
<circle cx="60" cy="20" r="15" fill="red"/>
<circle cx="100" cy="20" r="15" fill="green"/>
<circle cx="140" cy="20" r="15" fill="blue"/>
</svg>
(maroon/silver)
</div>
有更好的方法吗?
如果没有,哪里是放置修复功能挂钩的正确位置?它可以在哪里与用户覆盖和暗模式插件配合?
理想情况下,我会尊重用户的选择,默认情况下不运行 JavaScript。我添加了
@media (prefers-color-scheme: *)
来确保可容忍的默认值(如图所示),但结果却适得其反。主页可能不遵循相同的设置,如果我手动强制背景颜色与前景色相匹配,那么我似乎无法像修复描边颜色那样在 JavaScript 中修复它。
currentcolor
关键字,如 MDN Web 文档中所述:
关键字表示元素的currentcolor
属性的值。这使您可以在默认情况下不接收该值的属性上使用color
值。color
svg {
stroke-width:2;
fill-opacity:0.35;
stroke: currentColor;
}
<div>
sample text
<svg width="180" height="40" id="testpattern">
<circle cx="20" cy="20" r="15" fill="grey"/>
<circle cx="60" cy="20" r="15" fill="red"/>
<circle cx="100" cy="20" r="15" fill="green"/>
<circle cx="140" cy="20" r="15" fill="blue"/>
</svg>
(default colours)
</div>
<div style="color:yellow; background:navy">
sample text
<svg width="180" height="40">
<circle cx="20" cy="20" r="15" fill="grey"/>
<circle cx="60" cy="20" r="15" fill="red"/>
<circle cx="100" cy="20" r="15" fill="green"/>
<circle cx="140" cy="20" r="15" fill="blue"/>
</svg>
(yellow/navy)
</div>
<div style="color:maroon; background:silver">
sample text
<svg width="180" height="40">
<circle cx="20" cy="20" r="15" fill="grey"/>
<circle cx="60" cy="20" r="15" fill="red"/>
<circle cx="100" cy="20" r="15" fill="green"/>
<circle cx="140" cy="20" r="15" fill="blue"/>
</svg>
(maroon/silver)
</div>