准确定位HTML元素在SVG上方

3
我有一个包含SVG的HTML页面。我想要以编程方式将HTML元素(确切地说是输入元素)放置在SVG上方。
我知道元素所需的位置是相对于SVG宽度和高度的百分比。
我该如何将元素放置到指定位置?
我的一个想法是,在SVG周围放置一个具有完全相同尺寸的div,然后可以执行以下操作:
<div ...>
    <svg>...</svg>
    <input style="top:10%..."/>
    ...
</div>

如果要实现这一点,外部div必须具有与SVG完全相同的尺寸,但我不知道如何做到这一点。SVG只有一个viewBox属性,没有"width"和"height"属性。


1
将输入元素放置在SVG的foreignObject元素中,并根据需要定位foreignObject元素。 - Robert Longson
@RobertLongson 嘿,那是个好主意,谢谢。但不幸的是,我所拥有和必须使用的数据结构已经给定了。它是一个带有百分比位置的SVG +输入元素。 - Nathan
1个回答

0
position: relative; 设置给 "wrapper",并将 position: absolute; 设置给内部元素。此外,您需要设置包装器的大小(宽度和高度),以使 % 位置在内部起作用。

.wrap {
   position: relative;
    width: 200px;
    height: 200px;
}

.svg {
    position: absolute;
    top: 0;
    left: 0;
    width: 200px;
    height: 200px;
    background-color: orange;
}

.wrap input {
    position: absolute;
    left: 20px;
}
<div class="wrap">
    <div class="svg"></div><!-- just cheating the svg with bg-color -->
    <input type="text" style="top: 10%;" >
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接