这里有一个代码演示 http://jsfiddle.net/y59MR/1/
我有一个高度未知的 SVG。我可以在加载 json 并使用 javascript+math 后弄清楚它,但是有没有可以使用的 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>
如果 SVG 元素没有任何宽度和高度属性,则宽度/高度应为根据CSS规范计算 http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width正如罗伯特·朗森所指出的。但是,这些值不会反映 SVG 内容的正确尺寸。您可以使用以下方法找出正确的尺寸和位置getBBox()
:
// Javascript to run after document load
var svg = document.getElementsByTagName("svg")[0];
var bbox = svg.getBBox();
svg.setAttribute("width", bbox.width + "px");
svg.setAttribute("height", bbox.height + "px");
svg.setAttribute("viewBox", `${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`);
<svg xmlns="http://www.w3.org/2000/svg" style="background-color: red">
<rect x="30" y="40" width="50" height="60"/>
</svg>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)