我正在尝试在d中保存文本高度值(以便可以在适当大小的矩形周围绘制),但未在tick函数或其他任何地方定义。
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
});
我可以使其全球化吗?还是必须保存这些值?
最佳答案
看来您试图将高度字段附加到Node本身,通常认为这是一种不好的做法。
为什么不创建一个数据结构来存储所有这些值,或者甚至不增加数据集的高度。
另一种方法可能是在文本节点上创建数据高度属性。
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;
});