【发布时间】:2020-06-03 14:34:59
【问题描述】:
我正在尝试更改 <use> 元素的 width/height,according to the spec 和各种文档应该是可能的,只要它继承的元素确实如此没有设置这些属性。
不幸的是,如果 <rect> 没有设置 width 和 height 属性集,则似乎 <use> 元素根本不会显示。谁能解释一下?
如果您从一个不能具有width 和height 的元素继承,并且其尺寸以另一种方式描述(例如<circle>,其宽度和高度由其半径属性r 确定) 然后 <use> 元素 将 显示,但其 width 和 height 属性随后被忽略。而是使用半径值。
在任何情况下,如果我在symbol 中包装一个矩形定义(没有宽度或高度属性),并再次继承它,<use> 元素(设置了宽度和高度)将不会出现。
根据 SVG 1.1 规范,<use> 元素上的宽度和高度似乎并不真正起作用。显然,如果您没有在引用的元素上设置宽度和高度,它默认为自动(即零),我想之后设置宽度和高度只是缩放零尺寸或其他东西?
这是一个显示问题的小例子(在 Chrome、FF、Safari 和 Edge 上测试)。
/*selects a rect def*/
#rc {
width:24px;
height:24px;
}
/*selects a use instance*/
#u4 {
width:80px;
height:80px;
}
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="320px" height="240px" viewBox="0 0 320 240">
<defs>
<rect id="ra" width="20" height="10"/> <!-- width and height set in def -->
<rect id="rb" /> <!-- width and height omitted in def -->
<rect id="rc" /> <!-- width and height omitted in def -->
<rect id="rd" /> <!-- width and height omitted in def -->
<!-- defs wrapped in symbols -->
<symbol id="re" viewBox="0 0 20 20"><rect /></symbol>
<symbol id="cdef" viewBox="0 0 20 20" preserveAspectRatio="none">
<circle r="10" cx="10" cy="10" />
</symbol>
</defs>
<!-- using a def which includes width/height attributes (works) -->
<use href="#ra" id="u1" x="10" y="10" fill="pink"/>
<!-- setting width/height on use element (fails to display anything, but should work according to spec) -->
<use href="#rb" id="u2" x="30" y="10" width="20" height="20" fill="cyan" />
<!-- setting width/height of def in css (works) -->
<use href="#rc" id="u3" x="50" y="10" fill="slategray"/>
<!-- setting width/height of use in css (does fail, according to spec)-->
<use href="#rd" id="u4" x="50" y="10" fill="orange"/>
<!-- setting width/height of use, inheriting from symbol rather than a rect directly-->
<use href="#re" id="u4" x="60" y="20" width="20" height="20" fill="lime"/>
<!-- inheriting from a circle (which has no width/height attributes) instead of a rect-->
<use href="#cdef" id="u5" x="120" y="20" width="40" height="40" fill="blue" />
<!-- finally a plain old rect (for comparison) -->
<rect id="r1" x="150" y="10" width="32" height="24" stroke="black" fill="white" />
</svg>
您会注意到 orange 元素没有被绘制,这与预期的一样:根据规范,CSS 规则不能应用于<use> 元素,只能应用于它们继承的元素从。没关系。
但是 cyan 元素也没有被绘制,即使它设置了 width 和 height 属性。我可以让它出现的唯一方法是向<def> 添加宽度和高度,这意味着<use> 元素上的宽度和高度属性将被忽略,这完全违背了练习的对象。
也许有人可以解释在<use> 上设置width/height 应该如何工作,或者确认这是一个错误(在所有浏览器上!?)
【问题讨论】:
-
您可以在使用符号或带有viewBox属性的嵌套svg元素时设置宽度和高度
-
嗯.. 显然不是!我刚刚向包含矩形(石灰填充)的符号添加了一个视图框,但它仍然无法显示。
-
没有宽度和/或高度的矩形不是矩形
-
...如果继承的矩形设置了宽度和高度,则
-
标签: svg