无法在d3中选择SVG foreignObject元素 [英] Cannot select SVG foreignObject element in d3
问题描述
我正在使用d3强制导向的布局与HTML节点标签实现SVG foreignObject
元素。我想在不同的时间选择这些元素来更新他们的位置和其他属性(并跟踪他们创建和破坏与 enter()
和 exit()
),但我似乎不能像其他SVG元素一样选择它们。
I'm working with a d3 force-directed layout with HTML node labels implemented with SVG foreignObject
elements. I'd like to select these elements at various times to update their positions and other properties (and track them as they are created and destoryed with enter()
and exit()
), but I don't seem to be able to select them like other SVG elements.
示例:
HTML:
<html>
<head>
<title>Cannot Select SVG Foreign Object</title>
<script src="http://d3js.org/d3.v2.js"></script>
<script src = "fo_select.js"></script>
</head>
<body>
<svg id="example_svg" width="600" height="600">
<g>
<circle r="40" cx = "80" cy="80"></circle>
<foreignObject width = "100" height = "100" x = "200" y="200">
<body>Hello, world</body>
</foreignObject>
</g>
</svg>
<script>run()</script>
</body>
</html>
Javascript:
Javascript:
function run() {
svg = d3.select("#example_svg");
console.log(svg.selectAll("circle"));
console.log(svg.selectAll("foreignObject"));
}
这也在 http://bl.ocks.org/3217448 。控制台输出为:
This is also up at http://bl.ocks.org/3217448 . The console output is:
[Array[1]]
[Array[0]]
其中第一个数组包含 circle
元素,是空的。为什么 circle
对象是可选的,但 foreignObject
不是?我假设它与 foreignObject
的异常性质有关。我该如何选择它来操纵我的代码?非常感谢。
where the first array contains the circle
element, while the second one is empty. Why is the circle
object selectable, but the foreignObject
is not? I assume it has to do with the unusual nature of the foreignObject
. How would I select it to manipulate it in my code? Thanks very much.
推荐答案
严格来说,SVG是区分大小写的,所以你应该使用< foreignObject>
Strictly speaking, SVG is case sensitive so you should use <foreignObject>
instead of <foreignobject>
.
一个可能的解决方法是使用:
One possible workaround is to use:
.selectAll(function() { return this.getElementsByTagName("foreignObject"); })
(这可能不适用于旧的WebKit版本; WebKit bug 46800 。)
(This may not work in older WebKit versions though; see the now-closed WebKit bug 46800.)
或者,您可以使用CSS类或ID并选择您的元素。如果可能,我会推荐这种方法,考虑到各种上述错误。
Alternatively, you can use CSS classes or IDs and select your elements that way instead. I would recommend this approach at the moment if possible, given the various aforementioned bugs.
这篇关于无法在d3中选择SVG foreignObject元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!