问题描述
我知道SVG中有两种方法可以将形状分组在一起并将它们定位为集合:嵌套<svg>
标签和<g>
分组.但是,我认为它们之间没有太大区别.例如,以下两段代码产生完全相同的结果:
I know that there are two ways in SVG to group shapes together and position them as a collection: nesting <svg>
tag and <g>
grouping. However, I don't see much difference between them. For example, the following two pieces of code produce exactly the same result:
使用组(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>
哪个是首选/推荐?优点和缺点各有哪些重要特征?我对处理冒泡的点击事件问题特别感兴趣.
Which one is preferred/recommended? What are the pros and cons, important features of each? I am especially interested in handling bubbling click events issues.
推荐答案
在您的两个示例中,<svg>
和<g>
之间没有真正的区别.
In your two examples, there is no real difference between <svg>
and <g>
.
但是<svg>
可以执行<g>
不能执行的许多操作.组只是元素的被动组,他们真正能做的就是指定其子级都继承的某些属性.
However <svg>
can do many things that <g>
cannot. Groups are just a passive grouping of elements, and all they can really do is specify some properties that their children all inherit.
内部<svg>
元素建立一个新的视口.因此,您可以做最外面的<svg>
可以做的所有事情(实际上更多).
Inner <svg>
elements establish a new viewport. So you can do everything that the outermost <svg>
can (actually more).
例如,通过向内部SVG添加width
,height
和viewBox
属性,可以缩放其内容.
For example, by adding width
, height
and viewBox
attributes to the inner SVG, you can scale its contents.
<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规范中查看此.
This is not a very exiting example. Instead, have a look at this one from the SVG specification.
这篇关于SVG嵌套< svg> vs组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!