我正在对一些 javascript 进行维护,它使用.offsetParent http://www.quirksmode.org/js/findpos.html财产。最近的更改现在使应用程序使用 SVG 元素,并且它们破坏了 JavaScript,因为mySvgElement.offsetParent
总是undefined
.
Is .offsetParent
标准,并且它不适用于 SVG 元素吗?如果是这样,有什么替代方案.offsetParent
当使用 HTML5 SVG 元素时?
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());
}
这段代码取自here https://svn.apache.org/repos/asf/commons/sandbox/gsoc/2010/scxml-js/trunk/src/javascript/scxml/cgf/util/svg.js,并且是 Apache 许可的。 getBoundingBoxInArbitrarySpace 已经过测试,但 getBBoxInScreenSpace 还没有(但我认为它应该有效)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)