8

有没有办法 - 最好不使用 JavaScript - 将一些 HTML 内容放入 SVG 形状中foreignObject,这样 SVG 形状会自动调整大小(或缩放)以适应其内容?

即非常模糊的类似这个伪代码示例的东西,但有效,并且以我描述的方式起作用:

<?xml version="1.0" standalone="yes"?>
<svg xmlns = "http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="SCALE_TO_FIT_CONTENTS" height="SCALE_TO_FIT_CONTENTS" fill="gray">
    <foreignobject width="100%" height="100%">
      <body xmlns="http://www.w3.org/1999/xhtml">
        <div>Some HTML text</div>
      </body>
    </foreignobject>
  </rect>
</svg>
4

2 回答 2

3

如果不使用 javascript,就不可能做到这一点。事实上,SVG 形状不能用作容器。但是,我希望这是您所要求的:

<script type="text/javascript">
    function myFun(){
        var w = document.getElementById("myDiv").scrollWidth;
        document.getElementById("myRect").setAttribute("width",w);
    }
</script>
<svg xmlns = "http://www.w3.org/2000/svg" onload="myFun()">
    <rect id="myRect" x="10" y="10" width="0" height="100" fill="red"></rect>

        <foreignObject x="10" y="10" position="absolute" width="100%" height="100%">
            <div id="myDiv" style="display: inline-block;">Some HTML text that resizes its SVG container</div>
        </foreignObject>
</svg>
于 2012-07-19T14:56:37.107 回答
0

一个不错的技巧是将所有内容包装在一个<g>元素中,然后使用该元素测量该元素getBBox(),然后知道内部内容的高度,并可用于修改父SVG元素的高度。

var svg = document.querySelector('svg');
var bbox = svg.firstElementChild.getBBox();

svg.setAttribute("height", bbox.height + "px");
<svg>
  <g>
    <rect x="10" y="10" width="100" height="200px" fill="red"></rect>
        <foreignObject x="10" y="500" position="absolute" width="100%" height="100%">
            <div id="myDiv" style="display: inline-block;">Some HTML text that resizes its SVG container</div>
        </foreignObject>
        <text dy='500'>aaaaaaaaa</text>
  </g>
</svg>

于 2018-06-24T20:37:30.270 回答