SVG (可縮放向量圖形) 作為 XML 格式的向量圖形標準,可通過多種方式嵌入 HTML,各有優劣,選型需根據交互需求、性能、維護性決策。
| 方式 | 語法 | 優點 | 缺點 | 推薦場景 |
|---|---|---|---|---|
<embed> | <embed src="a.svg" type="image/svg+xml"> | 早期廣泛支持、可觸發插件安裝 | 非標準、難以用 JS 操作內部 DOM、安全限制多 | 舊專案維護、需插件回退 |
<object> | <object data="a.svg" type="image/svg+xml"></object> | 標準化、支持回退內容、可通過 contentDocument 訪問 SVG DOM | 跨域受同源策略限制、樣式隔離 | 需 JS 操作 SVG 內部、需回退內容 |
<iframe> | <iframe src="a.svg"></iframe> | 完全隔離、獨立文檔上下文 | 重量級、跨域通信複雜、樣式無法穿透 | 完全隔離的第三方 SVG、廣告位 |
| 內聯 SVG (推薦) | <svg>...</svg> 直接寫在 HTML | DOM 統一、CSS/JS 完全穿透、無額外請求、SEO 友好、可訪問性最佳 | HTML 體積增大、不利於複用 (可用 <symbol>+<use> 解決) | 現代首選、圖標系統、數據可視化、複雜交互 |
<svg width="100%" height="200" viewBox="0 0 400 200" xmlns="https://www.w3.org/2000/svg">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0)" />
<stop offset="100%" style="stop-color:rgb(255,0,0)" />
</linearGradient>
</defs>
<ellipse cx="200" cy="100" rx="180" ry="80" fill="url(#grad)" id="main-shape" />
<text x="200" y="105" text-anchor="middle" fill="white" font-size="24">內聯 SVG</text>
</svg>
<script>
// 直接操作 SVG DOM,無需 contentDocument
const shape = document.getElementById('main-shape');
shape.addEventListener('click', () => {
shape.setAttribute('fill', shape.getAttribute('fill') === 'url(#grad)' ? 'red' : 'url(#grad)');
shape.setAttribute('rx', shape.getAttribute('rx') == '180' ? '150' : '180');
});
</script>
| 元素 | 關鍵屬性 | 說明 | 示例 |
|---|---|---|---|
<rect> | x, y, width, height, rx, ry | 矩形/圓角矩形 | <rect x="10" y="10" width="100" height="50" rx="5"/> |
<circle> | cx, cy, r | 圓形 | <circle cx="50" cy="50" r="40"/> |
<ellipse> | cx, cy, rx, ry | 橢圓 | <ellipse cx="200" cy="100" rx="100" ry="50"/> |
<line> | x1, y1, x2, y2 | 直線 | <line x1="0" y1="0" x2="200" y2="200"/> |
<polyline> | points="x1,y1 x2,y2 ..." | 開放折線 | <polyline points="0,100 50,50 100,100"/> |
<polygon> | points="x1,y1 x2,y2 ..." | 閉合多邊形 | <polygon points="100,10 40,198 190,78 10,78 160,198"/> |
<path> | d="M... L... C... Z" | 任意路徑 (最強大) | <path d="M10 10 H 90 V 90 H 10 L 10 10"/> |
<svg style="display:none">
<symbol id="icon-home" viewBox="0 0 24 24">
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
</symbol>
<symbol id="icon-user" viewBox="0 0 24 24">
<path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
</symbol>
</svg>
<!-- 使用 -->
<svg class="icon"><use href="#icon-home"></use></svg>
<svg class="icon"><use href="#icon-user"></use></svg>
<style>
.icon { width: 24px; height: 24px; fill: currentColor; }
</style>
內聯 SVG 在 HTML5 中無需聲明 DTD,直接使用 <svg xmlns="https://www.w3.org/2000/svg"> 即可。舊版 XHTML/SVG 1.1 需要完整 DOCTYPE,現代項目可忽略。