typescript 需要在svg中更改foreignObject的高度

kr98yfug  于 7个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(81)

我需要在svg中动态地改变foreignObject的高度。我必须使用foreignObject,因为我需要在里面包含html元素。(我正在使用ngx-graph)。

<foreignObject x="1" y="1" width="335" [height]="foreignObjHeight(node.Data.length)" class="{{ checkIfSourceNode(node) }}">
...
</foreignObject>

字符串
我得到错误:

TypeError:无法设置只有getter的[object SVGForeignObjectElement]的属性高度

救命啊!

trnvg8h3

trnvg8h31#

在你的例子中,你可以只设置height属性为它的值:

<foreignObject x="1" y="1" width="335" [attr.height]="foreignObjHeight(node.Data.length)" ">

字符串

pinkon5k

pinkon5k2#

您可以使用ResizeObserver。在下面的示例中,foreignObject元素的子元素(childspan)将被更改大小,此时foreignObject的宽度和高度将被更新

let foreignbox, childspan;
function foreignsize() {
    if ( !foreignbox ) foreignbox = document.getElementById("forobjquestion");
    if ( !childspan ) childspan = document.getElementById("inputhtml");
    let spanBB = childspan.getBoundingClientRect();
    if ( foreignbox ) {
      foreignbox.setAttribute("width", spanBB.width/5); 
      foreignbox.setAttribute("height", spanBB.height/5); 
    }
  }
new ResizeObserver(foreignsize).observe(parentspan);

字符串
HTML

<foreignObject id="forobjquestion" x="0" y="0" width="100" height="100" xmlns="http://www.w3.org/2000/svg" >
    <span id="parentspan" >
        <xhtml:span id="inputhtml" >
            <xhtml:p id="mypid">123</xhtml:p>
        </xhtml:span>
    </span>
</foreignObject>

相关问题