css - 在 SVG 文件中更改背景时将笔划从黑色更改为白色
问题描述
我有一个绘制在白色背景上的 SVG 文件。
如果用户选择在黑色背景上显示,则所有呈现为黑色的路径都会消失。
是否可以更改 SVG 文件中呈现为黑色的所有元素,以便它们呈现为白色?包括路径、文本等。
SVG 是在浏览器中查看的,所以如果这可以在 CSS 和 javascript 中完成,我想这样做。
抱歉:SVG 中有 256 种颜色。
我制作了一个测试svg,如下所示:
<svg
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="fgc">
<stop stop-color="blue"/>
</linearGradient>
</defs>
<g id="layer1" >
<rect
style="stroke:url(#fgc);fill: none;"
id="rect10"
width="110"
height="75"
x="50"
y="55" />
</g>
</svg>
我从 HTML 页面调用它:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="application/x-javascript">
var drg="";
var svgDoc="";
var svgItem="";
window.onload=function() {
drg = document.getElementById("drawing");
svgDoc = drg.contentDocument;
svgItem = svgDoc.getElementById("fgc");
console.log(svgItem.getAttribute("stop-color"));
svgItem.setAttribute("stop-color", "red");
console.log(svgItem.getAttribute("stop-color"));
};
</script>
</head>
<body>
<object id="drawing" data="drawing.svg" type="image/svg+xml" width="200" height="150"></object>
</body>
</html>
console.log(svgItem.getAttribute("stop-color")) 在 svgItem.setAttribute("stop-color", "red") 和之后的 "red" 之前在浏览器控制台中打印 "null"。
矩形呈现为蓝色。
显然,将 window.onload 中的“停止颜色”属性更改为红色将不起作用,因为 svg 图形已经加载。如何在加载之前设置我的图形以呈现红色?
另外,我希望 console.log(svgItem.getAttribute("stop-color")) 在更改之前给我“蓝色”,但它给了我“null”,这一定意味着我正在更改错误的属性。
解决方案
这是可能的。
如果用户选择在黑色背景上显示,则所有呈现为黑色的路径都会消失。
当用户更改背景时,将类添加到 svg 的父级,例如bg-black
. 当用户将背景更改为白色时删除此类。
在 CSS 中,您可以像这样更改颜色。
.bg-black svg path,
.bg-black svg circle {
stroke: white !important;
}
.bg-black svg text {
fill: white !important;
}
推荐阅读
- r - 根据矩阵中的单元格值删除列并消除下标越界错误
- python-3.x - 如何将tableWidget中的数据插入sqlite数据库
- reactjs - d3.js + react.js --> 无法访问状态
- maven - Maven 编译器错误 - 无效标志 - 发布
- c# - How to retry a NUnit TestCase?
- laravel - Laravel, relationship problems
- javascript - Implementing Ecwid on a Angular 8 Application with script tags
- servlets - 无法初始化类 com.kaltura.client.Client
- r - 库(venn),更改字体大小
- c# - Owned types collection is never updated in EF Core