获取 SVG 元素的宽度/高度

新手上路,请多包涵

获取 svg 元素尺寸的正确方法是什么?

http://jsfiddle.net/langdonx/Xkv3X/

铬 28:

 style x
client 300x100
offset 300x100

即 10:

 stylex
client300x100
offsetundefinedxundefined

火狐 23:

 "style" "x"
"client" "0x0"
"offset" "undefinedxundefined"

svg1 上有宽度和高度属性,但是 .width.baseVal.value 仅当我在元素上设置宽度和高度属性时才设置。


小提琴看起来像这样:

HTML

 <svg id="svg1" xmlns="http://www.w3.org/2000/svg" version="1.1">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="1" fill="red" />
    <circle cx="150" cy="50" r="40" stroke="black" stroke-width="1" fill="green" />
    <circle cx="250" cy="50" r="40" stroke="black" stroke-width="1" fill="blue" />
</svg>

JS

 var svg1 = document.getElementById('svg1');

console.log(svg1);
console.log('style', svg1.style.width + 'x' + svg1.style.height);
console.log('client', svg1.clientWidth + 'x' + svg1.clientHeight);
console.log('offset', svg1.offsetWidth + 'x' + svg1.offsetHeight);

CSS

 #svg1 {
    width: 300px;
    height: 100px;
}

原文由 Langdon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

使用 getBBox 功能:

SVGGraphicsElement.getBBox() 方法允许我们确定对象适合的最小矩形的坐标。 […]

http://jsfiddle.net/Xkv3X/1/

 var bBox = svg1.getBBox();
console.log('XxY', bBox.x + 'x' + bBox.y);
console.log('size', bBox.width + 'x' + bBox.height);

原文由 Pavel Gruba 发布,翻译遵循 CC BY-SA 4.0 许可协议

FireFox 有 getBBox() 的问题,我需要在 vanillaJS 中执行此操作。

我有一个更好的方法,结果与真正的 svg.getBBox() 函数相同!

有了这篇好文章: 获取 SVG/G 元素的真实大小

var el   = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle

console.log( rect.width );
console.log( rect.height);

原文由 obysky 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题