簡體   English   中英

如何設置 SVG 樣式<g>元素?

[英]How to style SVG <g> element?

我有一些 SVG 元素組合在一個<g>元素中。 我只想設置<g>元素的樣式以顯示元素分組。 就像我想給它一些背景顏色和邊框一樣。 如何實現?

我嘗試了<g>元素的fillstroke屬性,但它不起作用。 怎么可能? 提前致謝!

樣品在這里

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
    <g fill="blue" stroke="2">
            <rect id="svg_6" height="112" width="84" y="105" x="136" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="5" stroke="#000000" fill="#00ff00"/>
        <ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="271" cy="156" id="svg_7" rx="64" ry="56"/>
    </g>
</svg>

您不能向 SVG <g>元素添加樣式。 它的唯一目的是將孩子分組。 這也意味着,您賦予它的樣式屬性會傳遞給它的子項,因此<g>上的fill="green"意味着其子項<rect>上的自動fill="green" (只要它沒有自己的fill規范)。

您唯一的選擇是向 SVG 添加一個新的<rect>並相應地放置它以匹配<g>子項的尺寸。

你實際上不能繪制容器元素

但是你可以使用一個帶有“SVG”的“foreignObject”來模擬你需要的東西。

http://jsfiddle.net/VBmbP/4/

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
      <foreignObject id="G" width="300" height="200">
        <svg>
          <rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>
          <ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/>     
        </svg>
          <style>
              #G {
                background: #cff; border: 1px dashed black;
              }
              #G:hover {
                background: #acc; border: 1px solid black;
              }
          </style>
      </foreignObject>
    </svg>

我知道在這個問題被提出和回答之后很久了 - 我確信接受的解決方案是正確的,但是當我可以用直接 CSS 實現相同或相似時,我的純粹主義者寧願不向 SVG 添加額外的元素。

雖然您確實無法以大多數方式設置g容器元素的樣式 - 您絕對可以為其添加輪廓並設置樣式 - 甚至在g懸停時更改它 - 如代碼段所示。

它在某一方面不如其他方式好 - 您可以將輪廓框放在分組元素周圍 - 但不能在其后面放置背景。 所以它並不完美並且不會為每個人解決問題 - 但我寧願用 css 完成大綱,而不是為了提供樣式掛鈎而必須向代碼添加額外的元素。

這種方法絕對允許您在 SVG 中顯示相關對象的分組。

只是一個想法。

 g { outline: solid 3px blue; outline-offset: 5px; } g:hover { outline-color: red }
 <svg width="640" height="480" xmlns="http://www.w3.org/2000/svg"> <g> <rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/> <ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/> </g> </svg>

您賦予“g”元素的樣式將應用子元素,而不是“g”元素本身。

在要設置樣式的組周圍添加一個矩形元素和位置。

請參閱: https : //developer.mozilla.org/en-US/docs/Web/SVG/Element/g

編輯:更新措辭並在評論中添加小提琴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM