如何获取HTML5 SVG元素中所有元素的位置
答
var children = $('svg').children();
for(var i in children) {
childLoop(children[i]); // Start with children because I don't think svg has
// A getBBox() method (only groups, rects, text..etc)
}
function childLoop(obj) {
alert($(obj).getBBox()); // Display the objects bounding box
// Bounding boxes have .x, .y,
// .width, and .height properties
for(var a in $(obj)[0].attributes) {
alert(a + '=' + $(obj)[0].attributes[a]);
}
for(var i in $(obj).children()) {
childLoop($(obj).children()[i]); // Do it for the rest of the children
}
}
基本上你需要选择SVG对象中的元素,并调用.getBBox()
方法就可以了。
这将返回一个对象具有以下结构(在位置(0所使用的对象,0)与100×100的尺寸例如):
.getBBox() : {
x: 0
y: 0
width: 100
height: 100
}
+0
某些元素可能具有与之相伴的文本和/或颜色,我将如何检索这些属性? – 2012-07-28 04:15:48
+0
看看我的编辑。我认为这可能有效......如果你知道所有的属性,你可以使用'$(obj).attr('fill')'例如 – 2012-07-28 13:09:11
需要在[接受答案]的习惯来获得( http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)帮助你解决你的问题。您将获得积分,其他人将被鼓励帮助您。 – 2017-07-12 12:52:19