【问题标题】:How to insert an element in a very specific place using D3如何使用 D3 在非常特定的位置插入元素
【发布时间】:2013-11-04 15:37:26
【问题描述】:

假设我有以下 DOM 结构:

div
  > svg
    > defs
    > g
      > rect
      > g
      > g
          <-- I want to insert an element here
      > g
      > g

g 的子 g 元素都没有类、id 或任何其他我可以用作选择器的元素,我无法修改它们,因为它们来自加载到页面。

到目前为止,我能做的最好的事情就是插入第三个g 元素,但这是不可接受的。我想在当前索引 2 和 3 之间(如果不计算 rect,则在索引 1 和 2 之间)向父 g 的孩子添加第 6 个元素。

这是我到目前为止所做的:

var test = d3.selectAll('#continer svg > g > g');
test = d3.select(test[0][2]);
test.append('foreignObject').
    attr('width', 690).attr('height', 500)
    .append('xhtml:body').style('font', '14px "Helvetica Neue"')
    .html('<h1>An HTML Foreign Object in SVG</h1>');

我最终得到以下结构:

div
  > svg
    > defs
    > g
      > rect
      > g
      > g
      > g
        > foreignobject & its children inserted here
      > g

...我明白为什么。我试过 D3 的 insert 方法,使用函数作为第二个参数来指定 before,但浏览器一直告诉我:

试图在不存在的上下文中引用节点 存在。

【问题讨论】:

    标签: dom svg d3.js


    【解决方案1】:

    好的,所以这可行,但它有点像黑客。在使用 D3 追加后,我使用 jQuery 重新排列元素。如果可能的话,仍然希望看到一个纯 D3 解决方案:

    // select the parent g element
    var parentG = d3.select('#continer svg > g');
    
    // append a new G element with a nested foreign object
    parentG.append('g').attr('id', '__my_custom_id')
        .append('foreignObject').attr('width', 690).attr('height', 500)
        .append('xhtml:body').style('font', '14px "Helvetica Neue"')
        .html('<h1>An HTML Foreign Object in SVG</h1>')
    ;
    
    // now use jQuery to rearrange the order of the elements
    $('#__my_custom_id')
        .insertAfter('#container svg > g > g:nth-child(3)')
        .removeAttr('id')
    ;
    

    【讨论】:

      猜你喜欢
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2011-03-22
      相关资源
      最近更新 更多