我知道在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>使用<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>哪一个是首选/推荐的?每种方法的优缺点和重要特征是什么?我对处理冒泡点击事件问题特别感兴趣。
发布于 2016-08-16 02:13:11
在您的两个示例中,<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>
这不是一个非常令人兴奋的例子。相反,可以使用来自SVG规范的look at this one。
https://stackoverflow.com/questions/38959079
复制相似问题