0

I am trying to save text height value in d (so I can draw around appropriate size rectangle), but it's not defined in tick function or any where else.

d.height

should hold values. (but it doesn't)

So I have tick function (part of it):

  function tick() {
    z.attr('d', function(d) {
    alert (d.height); //not defined
var sourceX = d.source.x + textWidth/2 + 10,
    sourceY = d.source.y + d.height/2 + 10,
    targetX = d.target.x + textWidth/2 + 10,
    targetY = d.target.y + d.height/2 + 10;      

return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
});

shape.attr('transform', function(d) {
middle_rect.attr("height", d.height/2 + 20);        
side_rect.attr("height", d.height/2 + 20);   
return 'translate(' + d.x + ',' + d.y + ')';        
});

And here how I'm trying to save values (bottom of code)

     shape = shape.data(nodes);
// add new nodes
 var g = shape.enter().append('svg:g').attr('class', function(d) { return d.type +'        node'; });

   middle_rect = svg.selectAll(".middle")
   .append("svg:rect")
   .attr("rx", "10")
   .attr("ry", "10")
   .style("stroke", "rgb(47,136,214)")
   .style("fill", "url(#middle_gradient)");


  side_rect = svg.selectAll(".side")
   .append("svg:rect")
   .attr("rx", "10")
   .attr("ry", "10")
   .style("stroke", "rgb(47,136,214)")
   .style("fill", "url(#side_gradient)");



  txt = g.append('svg:text')
   .attr('class',function (d){return 'bigest ' + d.id ;}  )
   .attr('y', ".5em")
   .attr("dy", "1em")
   .style("fill", "black")
   .each (function (d) {
    d.height =  this.getBoundingClientRect().height;
    // alert (d.height); //here I have this value
});

Can I make it global? Or have to save these values?

4

1 回答 1

2

您似乎正在尝试将高度字段附加到节点本身,这通常被认为是一种不好的做法。

为什么不创建一个数据结构来存储所有这些值,或者甚至可能将高度添加到您的数据集中。

另一种方法可能是在文本节点上创建数据高度属性。

http://jsfiddle.net/heavyhorse/893jT/

svg.selectAll('text.data-label').each(function(d, i){
    var height = this.getBoundingClientRect().height;
    var width = this.getBoundingClientRect().width;
    console.log(i+': ('+width+','+height+')');

    // create custom data-attr:
    this.setAttribute('data-width', width);
    this.setAttribute('data-height', height);
    console.log(this);

    // attach to dataset:
    dataset[i].width = width;
    dataset[i].height = height;
});
于 2013-10-28T17:27:52.653 回答