我学习 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/