javascript - 如何更改 `use` 元素使用的子项的属性?

标签 javascript css svg

我学习 SVG。我想更改第二个 use 的圆 fill 值。我该怎么做?这是我的尝试:

* {
	stroke: brown;
	stroke-width: 1;
	fill: none;
}

.canvas{
	border-color: green;
	border-style: solid;
	border-width: 1px;
}

.sun > circle{
	fill: yellow;
}

.hot-sun > circle {
	fill: red;
}
<?xml version='1.0'?>
<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/DTD/svg11.dtd'>
<?xml-stylesheet type='text/css' href='../css/index.css'?>
<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='1400' height='1000' viewBox='0 0 1400 1000' class='canvas'>
	<title>SVG learning</title>
	<desc>This is my sandbox</desc>
	<defs> 
		<g id='foo' class='sun'>
			<rect x='0' y='0' width='50' height='50'/>
			<circle cx='25' cy='25' r='10'/>
		</g>
	</defs>
	<g id='dwg'>
		<use xlink:href='#foo' transform='translate(10 10)' />
    <!-- Here I expected my sun will be red...-->
		<use xlink:href='#foo' transform='translate(10 70)' class='hot-sun'/>
	</g>
</svg>

最佳答案

您不能通过 CSS 选择 use 元素的子元素,因为它们不是 DOM 的一部分。尽管如此,use 元素本身的 CSS 属性可以被继承。因此,只要您不对 <defs> 中定义的引用元素设置样式即可。 , <use> 的样式将占上风。

注意不能有* { fill:...}规则。它将设置 defs > #foo > circle 的样式元素,这将优先于从 use 继承。元素。这就是为什么第二个太阳的笔触仍然是棕色的,尽管我定义了将其涂成绿色的规则。

* {
	stroke: brown;
	stroke-width: 1;
}

#foo rect {
	fill: none;
}

.canvas{
	border-color: green;
	border-style: solid;
	border-width: 1px;
}

use {
	fill: yellow;
}

.hot-sun {
	fill: red;
	stroke: green
}
<?xml version='1.0'?>
<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/DTD/svg11.dtd'>
<?xml-stylesheet type='text/css' href='../css/index.css'?>
<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='1400' height='1000' viewBox='0 0 1400 1000' class='canvas'>
	<title>SVG learning</title>
	<desc>This is my sandbox</desc>
	<defs> 
		<g id='foo' class='sun'>
			<rect x='0' y='0' width='50' height='50'/>
			<circle cx='25' cy='25' r='10'/>
		</g>
	</defs>
	<g id='dwg'>
		<use xlink:href='#foo' transform='translate(10 10)' />
    <!-- Here I expected my sun will be red...-->
		<use xlink:href='#foo' transform='translate(10 70)' class='hot-sun'/>
	</g>
</svg>

关于javascript - 如何更改 `use` 元素使用的子项的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45799737/

相关文章:

javascript - 如何在d3中右对齐两个文本

c# - 您能否将 XAML 绘图图像转换回 SVG 以进行编辑?

javascript - 没有参数的 typescript 回调函数?

javascript - 如何将可拖动元素返回到选项中?

css - 对于任何元素,在 CSS 重置(以及 eric meyer 重置)中包含哪些其他内容会很好

html - 对齐 flex 容器内的 <hr> 元素

javascript - for 循环中的条件语句简单如 i

javascript - 使用 Node.js 实时文本

html - 使用 YUI3 复制元素和子元素样式

canvas - 在 Famo.us 的表面之间画很多线?