最佳实践
本章节总结 SVG 开发中的最佳实践和常见模式,帮助你编写高质量、可维护的 SVG 代码。
代码组织
使用语义化标签
xml
<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>分组和命名
xml
<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>注释和文档
xml
<svg>
<!--
图标: 首页
用途: 导航栏主图标
作者: 开发团队
日期: 2024-01-01
-->
<symbol id="icon-home">
<path d="..."/>
</symbol>
</svg>可访问性
使用 title 和 desc
xml
<svg>
<title>网站导航图标</title>
<desc>包含首页、关于、联系三个导航按钮</desc>
<g role="navigation" aria-label="主导航">
<circle cx="50" cy="50" r="20" aria-label="首页"/>
</g>
</svg>添加 ARIA 属性
xml
<svg role="img" aria-labelledby="title desc">
<title id="title">图表标题</title>
<desc id="desc">这是一张展示销售数据的图表</desc>
<!-- 图表内容 -->
</svg>键盘导航
xml
<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>响应式设计
使用 viewBox
xml
<!-- 响应式 SVG -->
<svg viewBox="0 0 100 100" style="width: 100%; height: auto;">
<circle cx="50" cy="50" r="40"/>
</svg>CSS 媒体查询
xml
<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>使用 currentColor
xml
<svg viewBox="0 0 24 24" style="color: blue;">
<!-- 图标会继承父元素的颜色 -->
<path fill="currentColor" d="..."/>
</svg>性能优化
减少文件大小
- 使用 SVGOMG 优化
- 移除不必要的元数据
- 简化路径数据
复用元素
xml
<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>避免过度使用滤镜
xml
<!-- 避免:对大量元素应用滤镜 -->
<g filter="url(#blur)">
<!-- 100 个元素 -->
</g>
<!-- 好:只对必要元素应用滤镜 -->
<circle filter="url(#blur)"/>工具使用
推荐工具
-
设计工具
- Figma
- Adobe Illustrator
- Inkscape
-
优化工具
- SVGOMG
- SVGO
- SVG Cleaner
-
开发工具
- Chrome DevTools
- SVG Edit
- D3.js
工作流程
- 在设计工具中创建 SVG
- 导出为 SVG 文件
- 使用 SVGOMG 优化
- 在项目中引用
- 根据需要调整样式
常见陷阱
1. 命名空间
javascript
// 错误
const svg = document.createElement('svg');
// 正确
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');2. z-index
SVG 不支持 z-index,元素顺序决定层级:
xml
<!-- 蓝色圆形在下层 -->
<circle cx="50" cy="50" r="30" fill="blue"/>
<!-- 红色圆形在上层 -->
<circle cx="60" cy="60" r="30" fill="red"/>3. 事件冒泡
xml
<g onclick="handleGroupClick()">
<circle onclick="handleCircleClick(event)"/>
</g>
<script>
function handleCircleClick(e) {
e.stopPropagation(); // 阻止冒泡
}
</script>