2013-01-16 237 views
6

这里是一个code demo自动调整SVG大小?

我有一个未知的高度SVG。我可以在加载json并使用JavaScript +数学后找到它,但是有没有可用于动态调整大小的css?

CSS:

svg { 
    width: 500px; 
    height: 9000px; 
} 
.tabme { 
    border:3px solid red; 
    height: 200px; 
    overflow:scroll; 
} 

HTML:

<div class="tabme"> 
    <div id="Chart"> 
    <div class="chartbody" /> 
    <svg> 
     <rect width="190" y="0" height="16" x="175" /> 
     <rect width="190" y="20" height="16" x="175" /> 
     <rect width="190" y="40" height="16" x="175" /> 
     <rect width="190" y="60" height="16" x="175" /> 
     <rect width="190" y="80" height="16" x="175" /> 
     <rect width="190" y="100" height="16" x="175" /> 
     <rect width="190" y="120" height="16" x="175" /> 
     <rect width="190" y="140" height="16" x="175" /> 
     <rect width="190" y="160" height="16" x="175" /> 
     <rect width="190" y="180" height="16" x="175" /> 
     <rect width="190" y="200" height="16" x="175" /> 
     <rect width="190" y="220" height="16" x="175" /> 
     <rect width="190" y="240" height="16" x="175" /> 
     <rect width="190" y="260" height="16" x="175" /> 
     <rect width="190" y="280" height="16" x="175" /> 
     <rect width="190" y="300" height="16" x="175" /> 
    </svg> 
    </div> 
</div> 
+0

svg {height:100%;宽度:自动}可能是?它会像一个图像一样工作,并将200px高度,并将其保存在比例中。 – Flops

+0

@Flops:auto不起作用。还有我想要的高度 – BruteCode

回答

11

如果SVG元素没有任何width和height属性,则宽度/高度应calculated according to the CSS specs,如由罗伯特Longson指出。但是,这些值不会反映SVG内容的正确尺寸。您可以使用getBBox()找出适当的宽度/高度:

// Javascript to run after document load 
 
var svg = document.getElementsByTagName("svg")[0]; 
 
var bbox = svg.getBBox(); 
 
svg.setAttribute("width", bbox.x + bbox.width + "px"); 
 
svg.setAttribute("height",bbox.y + bbox.height + "px");
<svg xmlns="http://www.w3.org/2000/svg"> 
 
    <rect x="30" y="40" width="50" height="60"/> 
 
</svg>

+3

有规则定义在http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width中使用的宽度/高度,如果没有任何内容,则结果为300px x 150px更好。 –

+0

@RobertLongson:有趣的是,感谢那些信息!我的印象是结果不一致,但也许我的记忆是不准确的。我将更改答案以合并该信息。 –

+0

结果不一致,因为并非所有UA都已正确实施规则。 –

0

另一种方法是做类似上面的JS,但设置viewBox代替widthheight(注意,不是viewbox!)来自JS的值来自getBBox()的呼叫。然后使用preserveAspectRatio="xMidYMid meet"或类似的。

https://jsfiddle.net/t88pLgbb/4/