本章节总结 SVG 开发中的最佳实践和常见模式,帮助你编写高质量、可维护的 SVG 代码。
<svg>
<!-- 使用 defs 定义可复用元素 -->
<defs>
<symbol id="icon-home" viewBox="0 0 24 24">
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
</symbol>
</defs>
<!-- 使用 use 引用 -->
<use href="#icon-home" width="24" height="24"/>
</svg><svg>
<!-- 使用有意义的 ID -->
<g id="navigation">
<circle id="home-button" cx="50" cy="50" r="20"/>
<text id="home-label">Home</text>
</g>
<!-- 使用 class 分组样式 -->
<g class="icons">
<circle class="icon-bg" cx="100" cy="50" r="20"/>
<circle class="icon-bg" cx="150" cy="50" r="20"/>
</g>
</svg><svg>
<!--
图标: 首页
用途: 导航栏主图标
作者: 开发团队
日期: 2024-01-01
-->
<symbol id="icon-home">
<path d="..."/>
</symbol>
</svg><svg>
<title>网站导航图标</title>
<desc>包含首页、关于、联系三个导航按钮</desc>
<g role="navigation" aria-label="主导航">
<circle cx="50" cy="50" r="20" aria-label="首页"/>
</g>
</svg><svg role="img" aria-labelledby="title desc">
<title id="title">图表标题</title>
<desc id="desc">这是一张展示销售数据的图表</desc>
<!-- 图表内容 -->
</svg><svg>
<g tabindex="0" role="button" aria-label="点击下载">
<rect x="0" y="0" width="100" height="40"/>
<text x="50" y="25">下载</text>
</g>
</svg><!-- 响应式 SVG -->
<svg viewBox="0 0 100 100" style="width: 100%; height: auto;">
<circle cx="50" cy="50" r="40"/>
</svg><svg viewBox="0 0 100 100">
<style>
@media (max-width: 600px) {
.large-text { font-size: 12px; }
}
@media (min-width: 601px) {
.large-text { font-size: 24px; }
}
</style>
<text class="large-text">响应式文本</text>
</svg><svg viewBox="0 0 24 24" style="color: blue;">
<!-- 图标会继承父元素的颜色 -->
<path fill="currentColor" d="..."/>
</svg><svg>
<defs>
<!-- 定义一次 -->
<circle id="dot" r="5"/>
</defs>
<!-- 多次复用 -->
<use href="#dot" x="10" y="10"/>
<use href="#dot" x="20" y="20"/>
<use href="#dot" x="30" y="30"/>
</svg><!-- 避免:对大量元素应用滤镜 -->
<g filter="url(#blur)">
<!-- 100 个元素 -->
</g>
<!-- 好:只对必要元素应用滤镜 -->
<circle filter="url(#blur)"/>设计工具
优化工具
开发工具
// 错误
const svg = document.createElement('svg');
// 正确
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');SVG 不支持 z-index,元素顺序决定层级:
<!-- 蓝色圆形在下层 -->
<circle cx="50" cy="50" r="30" fill="blue"/>
<!-- 红色圆形在上层 -->
<circle cx="60" cy="60" r="30" fill="red"/><g onclick="handleGroupClick()">
<circle onclick="handleCircleClick(event)"/>
</g>
<script>
function handleCircleClick(e) {
e.stopPropagation(); // 阻止冒泡
}
</script>