16

在我的 SVG 中,我有一个包含 ap 元素的 foreignObject。我希望这个结构的高度适应我的文本高度。

p 元素已经适应:我没有为此做任何事情。

但是我对foreignObject有麻烦。如果我删除字段高度,它将不起作用。height:auto 也不起作用。

4

2 回答 2

20

由于没有真正使用放大和缩小foreignObject本身,因此您可以同时设置 foreignObjectheightwidthto 1,并通过 CSS setforeignObject { overflow: visible; }使其内容可见,无论它是什么,并用它做任何你需要做的事情。

于 2017-04-11T11:54:38.877 回答
10

foreignObject您可以以单位设置元素的高度em,也许这会有所帮助?

现在 a 的widthandheight属性foreignObject是必需的,并且必须具有 > 0 的值,否则该元素将不会被渲染。

更新:另一种方法是将 foreignObject 的尺寸设置为 100%,并使用 foreignObject 默认具有透明背景的事实。由于 svg 中的其他元素无论如何都以绝对方式布局,因此它们不依赖于 foreignObject 大小。

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <style>
    p { position: absolute; top: 50%; left: 50%; width: 100px; }
  </style>

  <circle cx="50%" cy="50%" r="25%" fill="lightblue"/>

  <foreignObject width="100%" height="100%">
    <p xmlns="http://www.w3.org/1999/xhtml">
        some wrapped text...
        some wrapped text...
        some wrapped text...
        some wrapped text...
    </p>
  </foreignObject>
</svg>
于 2013-04-29T09:11:16.413 回答