详细介绍SVG的tspan文本片段元素,学习如何在文本中创建不同样式的片段。通过实例掌握tspan的各种应用技巧。 tspan元素用于在text元素内部创建独立的文本片段,每个片段可以有自己的样式和定位。
<text>
<tspan>文本片段</tspan>
</text>
tspan最常用的功能是为文本的不同部分设置不同样式。
<text x="150" y="50" text-anchor="middle" font-size="20">
<tspan fill="#3498db">蓝色</tspan>
<tspan fill="#e74c3c">红色</tspan>
<tspan fill="#2ecc71">绿色</tspan>
</text>
<text x="150" y="85" text-anchor="middle" font-size="16">
<tspan font-weight="bold">粗体</tspan>和
<tspan font-style="italic">斜体</tspan>混合
</text>
tspan可以使用x、y、dx、dy属性进行独立定位。
<text font-size="18">
<tspan x="50" y="40" fill="#3498db">第一段</tspan>
<tspan x="150" y="40" fill="#e74c3c">第二段</tspan>
<tspan x="50" y="80" fill="#2ecc71">第三段</tspan>
<tspan x="150" y="80" fill="#f39c12">第四段</tspan>
</text>
<text x="30" y="50" font-size="18">
<tspan fill="#333">正常</tspan>
<tspan dy="-10" fill="#3498db">上移</tspan>
<tspan dy="20" fill="#e74c3c">下移</tspan>
<tspan dy="-10" fill="#2ecc71">恢复</tspan>
</text>
通过tspan的x和dy属性实现多行文本效果。
<text x="150" y="30" text-anchor="middle" font-size="14">
<tspan x="150" dy="0" font-weight="bold" font-size="18" fill="#333">标题文本</tspan>
<tspan x="150" dy="25" fill="#666">第一行内容描述</tspan>
<tspan x="150" dy="20" fill="#666">第二行内容描述</tspan>
<tspan x="150" dy="20" fill="#999" font-size="12">第三行小字说明</tspan>
</text>
利用dy属性可以轻松实现上标和下标效果。
<text x="50" y="50" font-size="20">
H<tspan dy="5" font-size="14">2</tspan><tspan dy="-5">O</tspan>
</text>
<text x="150" y="50" font-size="20">
X<tspan dy="-8" font-size="14">2</tspan><tspan dy="8"> + Y<tspan dy="-8" font-size="14">2</tspan><tspan dy="8"> = Z<tspan dy="-8" font-size="14">2</tspan>
</text>
tspan支持text-decoration属性实现下划线、删除线等效果。
<text x="150" y="40" text-anchor="middle" font-size="18">
<tspan text-decoration="underline">下划线</tspan>
</text>
<text x="150" y="70" text-anchor="middle" font-size="18">
<tspan text-decoration="line-through">删除线</tspan>
</text>
<text x="150" y="100" text-anchor="middle" font-size="18">
<tspan text-decoration="overline">上划线</tspan>
</text>
<text x="80" y="50">
<tspan font-size="16" fill="#999">¥</tspan>
<tspan font-size="32" font-weight="bold" fill="#e74c3c">99</tspan>
<tspan font-size="16" fill="#999">.00</tspan>
</text>
<text x="200" y="50">
<tspan font-size="14" fill="#999" text-decoration="line-through">¥199</tspan>
<tspan font-size="14" fill="#e74c3c" dx="10">5折</tspan>
</text>
<text x="150" y="50" text-anchor="middle" font-size="18">
搜索关键词:
<tspan fill="#e74c3c" font-weight="bold">SVG</tspan>
教程
</text>
| 属性 | 说明 |
|---|---|
| x, y | 绝对定位 |
| dx, dy | 相对偏移 |
| rotate | 旋转角度 |
| fill | 填充颜色 |
| stroke | 描边颜色 |
| font-* | 字体相关属性 |
| text-decoration | 文本装饰 |