代码之家  ›  专栏  ›  技术社区  ›  576i

如何定义一个模板来重用HTML/CSS中的SVG图形按钮?

  •  0
  • 576i  · 技术社区  · 5 年前

    对于仪表板html页面,我需要很多带有“-”或“+”符号的圆形按钮。

    按钮的外观如下:

    buttons

    下面的代码在Chromium中运行良好。

    重复每个按钮的完整设计会使代码难以阅读。

    对于每个按钮,只有 身份证件 以及文本 +/- 改变。

    是否有方法将其定义为 按钮模板 重用 按钮?

    <div class="item2" style="padding: 0px">
                    <svg id="minus1" height="60" width="60">
                        <circle cx="30" cy="30" r="28" stroke="black" stroke-width="2" fill="white"/>
                        <text x="15" y="48" fill="black" style="font-weight: bold;font-size: 50px;text-align: center;user-select: none">-</text>
                    </svg>
                </div>
                <div class="item2" style="padding: 0px">
                    <svg id="plus1" height="60" width="60">
                        <circle cx="30" cy="30" r="28" stroke="black" stroke-width="2" fill="white"/>
                        <text x="15" y="48" fill="black" style="font-weight: bold;font-size: 50px;text-align: center;user-select: none">+</text>
                    </svg>
                </div>
                <div class="item1"></div>
    0 回复  |  直到 5 年前
        1
  •  1
  •   Leo    5 年前

    你能做什么

    通过引用svg内容 id 具有 xlink:href 从a <use> 标签。

    怎么做

    1. 将每个内容分组 <svg> 如果还没有,请将其合并到一个标签中,以便以后可以通过添加 身份证件 到它。
    2. 包装共享相同内容的分组内容 viewBox (在你的例子中,所有这些都是绑定的),变成一个单一的 <defs> tag,用于存储稍后使用的内容的标签。
    3. <defs> 进入a <svg> 坚持这一点 viewBox 信息。
    4. 把决赛 <svg> 在你的 <body> (通常在顶部)。

    例如。

    经过一些修改的示例:

    text {
      font-weight: bold;
      font-size: 50px;
    }
    
    .svg-container {
      height: 60px;
      width: 60px;
      user-select: none;
    }
    
    svg {
      height: 100%;
      width: 100%;
    }
    <body>
      <svg viewBox="0 0 60 60" style="display: none">
        <defs>
          <g id="minus">
            <circle cx="30" cy="30" r="28" stroke="black" stroke-width="2" fill="white"/>
            <text x="21" y="44" fill="black">-</text>
          </g>
          <g id="plus">
            <circle cx="30" cy="30" r="28" stroke="black" stroke-width="2" fill="white"/>
            <text x="15" y="48" fill="black">+</text>
          </g>
        </defs>
      </svg>
    
      <!-- somewhere in your code -->
      <div class="svg-container">
        <svg>
          <use xlink:href="#minus" />
        </svg>
      </div>
      <div class="svg-container">
        <svg>
          <use xlink:href="#plus" />
        </svg>
      </div>
    </body>