我知道在 SVG 中有两种方法可以将形状组合在一起并将它们定位为一个集合:嵌套<svg>
标记和<g>
分组。但是,我看不出它们之间有太大区别。例如,以下两段代码产生完全相同的结果:
使用组(jsfiddle):https : //jsfiddle.net/8q4on01m/5/
<svg width="5000" height="5000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g transform="translate(200 200)">
<rect x="0" y="0" height="100" width="100" style="fill: yellow"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: green" transform="rotate(45) translate(200 100)"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: red" transform="translate(200 100)"></rect>
</g>
</svg>
Run Code Online (Sandbox Code Playgroud)
使用<svg>
(jsfiddle):
<svg width="5000" height="5000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<svg x="200" y="200">
<rect x="0" y="0" height="100" width="100" style="fill: yellow"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: green" transform="rotate(45) translate(200 100)"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: red" transform="translate(200 100)"></rect>
</svg>
</svg>
Run Code Online (Sandbox Code Playgroud)
哪一个是首选/推荐的?各自的优缺点和重要特征是什么?我对处理冒泡点击事件问题特别感兴趣。
Pau*_*eau 10
在您的两个示例中,<svg>
和之间没有真正的区别<g>
。
但是<svg>
可以做很多不能做的事情<g>
。组只是元素的被动分组,他们真正能做的就是指定一些他们的孩子都继承的属性。
内部<svg>
元素建立一个新的视口。所以你可以做最外层可以做的一切<svg>
(实际上更多)。
例如,通过向内部 SVG添加width
,height
和viewBox
属性,您可以缩放其内容。
<svg width="5000" height="5000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<svg x="200" y="200" width="100" height="100" viewBox="0 0 300 300">
<rect x="0" y="0" height="100" width="100" style="fill: yellow"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: green" transform="rotate(45) translate(200 100)"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: red" transform="translate(200 100)"></rect>
</svg>
</svg>
Run Code Online (Sandbox Code Playgroud)
这不是一个很老的例子。相反,请查看SVG 规范中的这个。