将SVG元素放置在另一个元素上

时间:2019-01-09 04:11:07

标签: html svg

我只是想知道是否可以将SVG元素放置在另一个元素上。这是我的HTML:

<svg id="svg" width="950" height="910" style="border: 2px rgb(204, 204, 204); margin-top: 10px;">
  <rect x="348" y="95" width="16" height="16" class="handle" polygonNo="0" pointNo="0"></rect>
  <rect x="582" y="95" width="16" height="16" class="handle" polygonNo="0" pointNo="1" style="
"></rect>
  <polygon points="348,206 598,206 598,106 348,106" id="polygon" polygonNo="1" fill="#8DB0F5"></polygon>
</svg>

我希望这两个矩形显示在多边形上;我曾尝试调整z-index,但似乎没有用。

3 个答案:

答案 0 :(得分:1)

更改顺序。较低级别的元素应首先写入。

<svg id="svg" width="950" height="910" style="border: 2px rgb(204, 204, 204); margin-top: 10px;">
          <polygon points="348,206 598,206 598,106 348,106" id="polygon" polygonNo="1" fill="#8DB0F5"></polygon>
          <rect x="348" y="95" width="16" height="16" class="handle" polygonNo="0" pointNo="0"></rect>
          <rect x="582" y="95" width="16" height="16" class="handle" polygonNo="0" pointNo="1" style=""></rect>
</svg>

替代解决方案

<svg viewBox="0 0 600 600" xmlns="http://www.w3.org/2000/svg">
  <rect x="348" y="95" width="16" height="16" class="handle" polygonNo="0" id="two" pointNo="0"></rect>
  <rect x="582" y="95" width="16" height="16" class="handle" polygonNo="0"  id="one" pointNo="1" style=""></rect>
  <polygon points="348,206 598,206 598,106 348,106" id="polygon" polygonNo="1" fill="#8DB0F5" ></polygon>
  <use xlink:href="#one"/>
  <use xlink:href="#two"/>
</svg>

答案 1 :(得分:1)

如果您有能力分离SVG元素,则也可以使用CSS定位来实现:

 .top{
position: absolute;
top: 34px;
left: 30px;
}
<svg class="top" id="svg" width="950" height="910" style="border: 2px rgb(204, 204, 204); margin-top: 10px;">
  <rect x="348" y="95" width="16" height="16" class="handle" polygonNo="0" pointNo="0"></rect>
  <rect x="500" y="95" width="16" height="16" class="handle" polygonNo="0" pointNo="1" style=""></rect>
</svg>

<svg class="bottom" id="svg" width="950" height="910" style="border: 2px rgb(204, 204, 204); margin-top: 10px;">
    <polygon points="348,206 598,206 598,106 348,106" id="polygon" polygonNo="1" fill="#8DB0F5"></polygon>
</svg>

希望有帮助!

答案 2 :(得分:1)

您还可以使用JavaScript进行操作。本质上,您是将2个矩形附加到SVG,从而将它们移动到多边形的顶部。

appendChild()将其元素从当前位置移动到新位置,并且不需要在再次附加节点之前从其父节点中删除该节点。

此外,SVG的边框没有border-style。您需要解决该问题。

let rects = svg.querySelectorAll(".handle");

rects.forEach(r=>{
  svg.appendChild(r)
})
<svg id="svg" width="950" height="910" style="border: 2px solid rgb(204, 204, 204); margin-top: 10px;">
  <rect x="348" y="95" width="16" height="16" class="handle" polygonNo="0" pointNo="0"></rect>
  <rect x="582" y="95" width="16" height="16" class="handle" polygonNo="0" pointNo="1" style="
"></rect>
  <polygon points="348,206 598,206 598,106 348,106" id="polygon" polygonNo="1" fill="#8DB0F5"></polygon>
</svg>

相关问题