如何通过百分比设置SVG宽度和高度?

40

我使用SVG创建了一条线,但是当我调整浏览器大小时,使用SVG创建的线没有随之缩放。

我尝试将SVG的宽度设置为百分比,但是这样做后线条就不出现了。我该如何通过百分比设置SVG的宽度?

<svg height="210" width="500">
  <line x1="380" y1="20" x2="230" y2="200" style="stroke: rgb(234, 243, 234); stroke-width: 5"></line>
</svg>
3个回答

55

我解决了我的问题。 我将我的代码更改为以下内容,现在可以正常工作:

<svg style="width:100%;height:100%;">
  <line x1="100%" y1="0%" x2="0%" y2="100%" style="stroke: rgb(234, 243, 234);stroke-width: 5;"></line>
</svg>

1
这对于<g>是有效的吗? - Darlan Dieterich

7

强制更新

<svg id="mySVG" height="210" width="500">...</svg>

js:

var mySVG = document.getElementById("mySVG");
mySVG.setAttribute("width",  window.innerWidth);
mySVG.setAttribute("height", window.innerHeight);

js + jQuery:

$(window).resize(function() {
    $("#mySVG").attr("width",  window.innerWidth);
    $("#mySVG").attr("height", window.innerHeight);
});

2

更改width属性的css样式

<svg width="10%">
  <line x1="380" y1="20" x2="230" y2="200" style="stroke: rgb(234, 243, 234); stroke-width: 5"></line>
</svg>

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