How to get SVG element dimensions in FireFox?

2019-01-18 10:38发布

In most browsers, the following would work.

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

Here is a demo. If you try it in Google Chrome, the console will output 200. However, FireFox returns 0.

标签: firefox svg
4条回答
乱世女痞
2楼-- · 2019-01-18 11:25

The solution I found for this was to use .getComputedStyle(). And since svg elements are not supported in old IE8- browsers, .getComputedStyle() is the way to give consistent results.

So I ended up using this function in my library:

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;
};
查看更多
【Aperson】
3楼-- · 2019-01-18 11:30

This Firefox bug was fixed in Firefox 33 which was released on 14 October 2014.

See bug 530985 for details.

查看更多
小情绪 Triste *
4楼-- · 2019-01-18 11:42

I've ended up falling back to the parent dimensions if SVG properties cannot be returned. Here is a demo http://jsbin.com/uzoyik/1/edit.

The relavent code is:

svg.clientWidth || svg.parentNode.clientWidth
svg.clientHeight || svg.parentNode.clientHeight
查看更多
Luminary・发光体
5楼-- · 2019-01-18 11:44

I don't think "width" is a standard cross-browser property of the object returned by the getBoundingClientRect method. I typically do something like:

var box = el.getBoundingClientRect();
var width = box.right-box.left;
var height = box.bottom-box.top;
查看更多
登录 后发表回答