如何在HTML SVG元素中使用`element.offsetParent`?

Ric*_*uen 6 javascript html5 svg

我正在使用一些使用该.offsetParent属性的javascript进行维护.最近更改现在可以选择使用SVG元素的应用,他们打破了JavaScript的,因为mySvgElement.offsetParent始终undefined.

.offsetParent标准的,它不适用于SVG元素吗?如果是这样,.offsetParent在使用HTML5 SVG元素时有什么替代方法?

jbe*_*rd4 6

SVG中不存在offsetParent.

要获取SVG节点的边界框坐标,通常会在SVG元素上使用getBBox方法.这将返回该元素的本地坐标系中的bbox.要确定屏幕坐标中SVG元素的位置,然后在元素上使用getScreenCTM来获取将该元素的本地坐标转换为屏幕坐标的变换矩阵.然后,您可以通过返回的转换矩阵转换返回的bbox.这是一些代码来执行此操作:

function getBoundingBoxInArbitrarySpace(element,mat){
    var svgRoot = element.ownerSVGElement;
    var bbox = element.getBBox();

    var cPt1 =  svgRoot.createSVGPoint();
    cPt1.x = bbox.x;
    cPt1.y = bbox.y;
    cPt1 = cPt1.matrixTransform(mat);

    // repeat for other corner points and the new bbox is
    // simply the minX/minY  to maxX/maxY of the four points.
    var cPt2 = svgRoot.createSVGPoint();
    cPt2.x = bbox.x + bbox.width;
    cPt2.y = bbox.y;
    cPt2 = cPt2.matrixTransform(mat);

    var cPt3 = svgRoot.createSVGPoint();
    cPt3.x = bbox.x;
    cPt3.y = bbox.y + bbox.height;
    cPt3 = cPt3.matrixTransform(mat);

    var cPt4 = svgRoot.createSVGPoint();
    cPt4.x = bbox.x + bbox.width;
    cPt4.y = bbox.y + bbox.height;
    cPt4 = cPt4.matrixTransform(mat);

    var points = [cPt1,cPt2,cPt3,cPt4]

    //find minX,minY,maxX,maxY
    var minX=Number.MAX_VALUE;
    var minY=Number.MAX_VALUE;
    var maxX=0
    var maxY=0
    for(i=0;i<points.length;i++)
    {
        if (points[i].x < minX)
        {
            minX = points[i].x
        }
        if (points[i].y < minY)
        {
            minY = points[i].y
        }
        if (points[i].x > maxX)
        {
            maxX = points[i].x
        }
        if (points[i].y > maxY)
        {
            maxY = points[i].y
        }
    }

    //instantiate new object that is like an SVGRect
    var newBBox = {"x":minX,"y":minY,"width":maxX-minX,"height":maxY-minY}
    return newBBox; 
}   

function getBBoxInScreenSpace(element){
    return getBoundingBoxInArbitrarySpace(element,element.getScreenCTM());
}
Run Code Online (Sandbox Code Playgroud)

此代码取自此处,并获得Apache许可.getBoundingBoxInArbitrarySpace已经过测试,但是getBBoxInScreenSpace还没有(但我觉得应该可行).