首页 > 解决方案 > 使用纯 SVG 将内联标签添加到水平条

问题描述

我使用波纹管 SVG 代码来构建水平条形图。没关系,但我还需要图表前后两个内联标签。我知道如何用 HTML 和 CSS 添加它们,但我只想用纯 SVG 来解决这个问题。这个怎么做?

  <svg class="chart" width="300px" height="40">
        <g transform="translate(0,0)">
            <rect width="82%" height="22" fill="lightskyblue"></rect>
            <rect width="100%" height="22" style="fill:none; stroke-width:1; stroke:gray;"></rect>
            <text y="30" dx="0.25em" dy=".35em">0</text>
            <text x="20%" y="10" dy=".35em" fill="red">|</text>
            <text x="20%" y="30" dx="-0.25em" dy=".35em" fill="red">13</text>
            <text x="100%" y="30" dx="-1.25em" dy=".35em">63</text>
        </g>
    </svg>

这就是我现在所拥有的:

在此处输入图像描述

这就是我想要的:

在此处输入图像描述

标签: svg

解决方案


为了使它工作,我将您的代码用作更大的 svg 元素中的嵌套 svg。请注意我正在使用 viewBox 属性,其中 x 组件具有负值 (-50) 为文本腾出空间。

svg{border:solid;}
<svg class="chart" width="300px" viewBox="-50 0 400 40">
  <text y="20" x="-45">TXT</text>
  <text x="345" y="20" text-anchor="end">TXT</text>
    <svg viewBox="0 0 300 40" width="300">
        <rect width="82%" height="22" fill="lightskyblue"></rect>
        <rect width="100%" height="22" style="fill:none; stroke-width:1; stroke:gray;"></rect>
        <text y="30" dx="0.25em" dy=".35em">0</text>
        <text x="20%" y="10" dy=".35em" fill="red">|</text>
        <text x="20%" y="30" dx="-0.25em" dy=".35em" fill="red">13</text>
        <text x="100%" y="30" dx="-1.25em" dy=".35em">63</text>
  </svg>
 </svg>

我必须告诉你,我不会对矩形的位置和大小进行百分比计算。我会使用用户单位(没有单位标识符)来完成它,我不需要将它包装在另一个 svg 元素中。

更新

OP正在评论

你能再举一个例子吗,没有矩形的位置和大小的百分比,也没有将它包装在另一个 svg 元素中

svg{border:solid}
<svg class="chart" width="300px" viewBox="-50 0 400 40">
  <text y="20" x="-45">TXT</text>
  <text x="345" y="20" text-anchor="end">TXT</text>
    
        <rect width="246" height="22" fill="lightskyblue"></rect>
        <rect width="300" height="22" style="fill:none; stroke-width:1; stroke:gray;"></rect>
        <text y="30" dx="0.25em" dy=".35em">0</text>
        <text x="60" y="10" dy=".35em" fill="red">|</text>
        <text x="60" y="30" dx="-0.25em" dy=".35em" fill="red">13</text>
        <text x="300" y="30" dx="-1.25em" dy=".35em">63</text>
  <svg>


推荐阅读