如何在FireFox中获取SVG元素的尺寸?

19

在大多数浏览器中,以下代码将有效。

window.onload = function(){
    console.log( document.getElementById('svgElm').getBoundingClientRect().width );
};

这里有一个演示。如果你在Google Chrome中尝试它,控制台将输出200。然而,FireFox返回0

4个回答

22

如果无法返回SVG属性,则我最终会回到父级尺寸。这里有一个演示http://jsbin.com/uzoyik/1/edit

相关代码如下:

svg.clientWidth || svg.parentNode.clientWidth
svg.clientHeight || svg.parentNode.clientHeight

14

我认为“宽度”不是由getBoundingClientRect方法返回的对象的标准跨浏览器属性。我通常会这样做:

var box = el.getBoundingClientRect();
var width = box.right-box.left;
var height = box.bottom-box.top;

2
我发现解决这个问题的方法是使用 .getComputedStyle()。由于旧版IE8-浏览器不支持svg元素,因此.getComputedStyle()是提供一致结果的方法。所以我最终在我的库中使用了这个函数:
var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
    widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];

var svgCalculateSize = function (el) {

    var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
        bounds = {
            width: 0,
            height: 0
        };

    heightComponents.forEach(function (css) { 
        bounds.height += parseFloat(gCS[css]);
    });
    widthComponents.forEach(function (css) {
        bounds.width += parseFloat(gCS[css]);
    });
    return bounds;
};

2
这个Firefox的bug在2014年10月14日发布的Firefox 33版本中已被修复。
详细信息请参见bug 530985

2
目前在Firefox 65.0.1(64位)中,对于svg元素,clientWidth和clientHeight总是返回0。但在Chrome中并非如此。但是getBoundingClientRect().width/height似乎可以工作。为什么会这样呢?根据MDN: Element.clientWidth属性对于内联元素和没有CSS的元素为零;否则,它是元素的像素内部宽度。然而,即使应用CSS也不能使clientWidth / Height正常工作,它似乎不是内联的。 - jeremykentbgross

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