2017-10-04 77 views
-1

我使用SVG製作的圖像,許多元素具有相同的屬性,即典型的元素看起來像:添加SVG屬性的一類

<line x1="30" y1="10" x2="270" y2="10" stroke-width="0.1" stroke="lightgray" stroke-dasharray="2.5 2.5"/> 

有很多這種類型的線,其中的只有變化的東西是座標。必須有一種方法來創建某種包含stroke-width,stroke和stroke-dasharray屬性的類?我正在重複自己很多,並且堵塞了一些代碼。

我試過使用CSS,但無法使用SVG屬性。有誰知道如何做到這一點?謝謝

+2

請添加一些代碼示例。沒有理由說CSS爲什麼不能用於SVG。例如。 'line {stroke:lightgray,stroke-dasharray:2.5,2.5; }'等https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes#Using_CSS – helb

+0

你有沒有嘗試過在JavaScript中實現這一點?或者你是否試圖去純粹的CSS/HTML路徑? – Matthew

+4

這些[樣式屬性](https://www.w3.org/TR/SVG11/styling.html#SVGStylingProperties)既可以用作屬性,也可以用作CSS樣式。 – ccprog

回答

0

正如在@ccprog的評論中提到的那樣,可以使用css設置一些styling attributes。所有其他屬性,如xy需要設置在元素本身。

如果你有大量的重複去,你可以考慮使用<defs><use>像這樣:

<svg> 
    <defs> 
    <line id="line-1" x="..." ... /> 
    </defs> 

    <use xlink:href="#line-1" transform="translate(...)" /> 
    <use xlink:href="#line-1" transform="rotate(...)" /> 
    <use xlink:href="#line-1" transform="translate(...) rotate(...)" /> 
    . 
    . 
    . 
</svg> 

這樣你就可以重新使用該行,是的,但你是有限的轉換,當談到重新排列它們。

請注意,SVG 2.0中的xlink:href的使用在<use>元素中被描述爲href

0

樣式屬性可以從它們的父元素繼承。因此,如果您有一堆具有相同屬性的行,那麼只需將它們包裝在一個組中,然後將屬性應用於該屬性即可。

<g stroke-width="0.1" stroke="lightgray" stroke-dasharray="2.5 2.5"/> 
    <line x1="30" y1="10" x2="270" y2="10"/> 
    <line x1="40" y1="10" x2="270" y2="30"/> 
    ...etc... 
</g>