2013-10-28 1 views
0

d에 텍스트 높이 값을 저장하려고합니다. (그래서 적절한 크기의 사각형을 그릴 수 있습니다.)하지만 틱 기능이나 다른 곳에서는 정의되지 않았습니다.d3 라이브러리를 사용하여 d로 텍스트 높이를 저장해야합니다.

d.height 

에는 값이 있어야합니다.

그래서 체크 한 기능 (의 일부) (그러나 그렇지 않습니다) :

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 + ')';   
}); 

그리고 여기 값 (코드 아래)

 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 
}); 
을 저장하기 위해 노력하고있어 방법

글로벌화 할 수 있습니까? 또는이 값을 저장해야합니까?

+0

? 어디에서 높이에 접근 할 수 있기를 원하십니까? .each 함수가 여러 항목을 통과하면 어떤 일이 일어나기를 원합니 까? – talegna

답변

2

일반적으로 나쁜 습관으로 간주되는 높이 필드를 노드 자체에 부착하려고 시도하는 것으로 보입니다.

이러한 모든 값을 저장하거나 데이터 세트에 높이를 추가하는 데이터 구조를 만들어 보지 마십시오.

또 다른 방법은 텍스트 노드에 데이터 높이 특성을 만드는 것입니다. 당신은 TXT 변수에 할당하려고 무엇

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; 
}); 
+0

방금 ​​내 생명을 구했어! : D 고마워! –

관련 문제