How to get SVG element dimensions in FireFox?

前端 未结 4 1082
轮回少年
轮回少年 2020-12-10 01:49

In most browsers, the following would work.

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


        
相关标签:
4条回答
  • 2020-12-10 02:29

    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
    
    0 讨论(0)
  • 2020-12-10 02:34

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

    See bug 530985 for details.

    0 讨论(0)
  • 2020-12-10 02:49

    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;
    
    0 讨论(0)
  • 2020-12-10 02:52

    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;
    };
    
    0 讨论(0)
提交回复
热议问题