Firefox svg 渲染:如何获得真正的 g 位置?

Firefox svg rendering: how to get real g position?

我有一个页面,其中包含通过对象加载的 svg。

然后,我调用一个函数来加载 div,使用内部 g 元素的宽度、高度、左侧和顶部

var cartina = document.getElementById(whatMap);
        var cartinaContext;         
        cartina.addEventListener("load",function(){
        cartinaContext = cartina.contentDocument;
        var el   = $("#mappaBase", cartinaContext)[0]; 
        var rect = el.getBoundingClientRect(); 
        var whatContainer = "#containerIcone"+whatMap;
        $(whatContainer).css("position", "absolute");
        $(whatContainer).width(rect.width);
        $(whatContainer).height(rect.height);
        $(whatContainer).css("left", rect.left);
        $(whatContainer).css("top", rect.top);
}

我正在使用 getBoundingClientRect()。我在 svg 上应用 div #containerIcone。 在 Chrome 中,它运行良好。问题出在 Firefox 中:当我加载页面时,宽度和高度已正确加载,但左侧和顶部未正确加载。如果我用 Firefox 检查 svg,看起来 g 元素被放置在一个固定的位置,而 rendered g 元素有另一个(响应 window 尺寸和其他元素位置)。不过,g 固定元素对 window 各种尺寸反应良好。 div 放置在 g 元素固定检查位置上。

用 Chrome 检查同一个元素显示 g 元素检查框每次在 g 渲染元素所在的位置绘制。

我怎样才能在 Firefox 中使用它?

我找到了一个解决方案,它可以跨浏览器工作。 我没有使用嵌套 g 元素的 .top 和 .left 定位,而是获得了嵌套元素的宽度和高度

var el   = $(nestedElement); 
var rect = el.getBoundingClientRect(); 

然后我得到父 svg 元素的宽度和高度

var rectSvg = mysvg.getBoundingClientRect();

然后我从 svg 中减去 el 宽度和高度,得到 divide 结果通过 2. 最终结果是白色 space svg 有 inside 它,顶部和左侧,用于居中渲染元素 el inside svg 元素(浏览器用来保持纵横比)。然后,我将这些结果应用为包含图标的 div 顶部和左侧的 css - 它将精确定位在 g el 元素上。

var leftSpace = (rectSvg.width - rect.width)/2;
var topSpace = (rectSvg.height - rect.height)/2;
$(myPositionedDiv).css("left", leftSpace);
$(myPositionedDiv).css("top", topSpace);

尽管 Firefox 以这种方式定位了元素,但仍会正确计算左侧和顶部。