必须使用 d3 库将文本高度保存在 d 中
Have to save text height in d using d3 library
我正在尝试将文本高度值保存在 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
});
我可以将其全球化吗?还是必须保存这些值?
您似乎正在尝试将高度字段附加到节点本身,这通常被认为是一种不好的做法。
为什么不创建一个数据结构来存储所有这些值,甚至可能将高度添加到数据集中。
另一种方法是在文本节点上创建数据高度属性。
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;
});
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- ExtJS——在展开/折叠时调整面板高度
- 分析高度属性时出现意外值{{specs.height}}.index.html
- 单击页面上的链接后高度发生变化
- 如何将getJson的响应保存在全局变量中
- 按下按钮时保存cookie
- 如何使用 Angular JS 将数据保存在数据库中
- 子字符串/正则表达式以获取字符串中保存的 SRC 值
- 不加载宽度和高度的角度pintura
- HTML5在画布中加载较小的图像并保存实际大小的图像
- 是否可以在浏览器中使用纯JavaScript保存音频流
- 如何将多个画布保存为一个图像
- 查找元素高度,包括边距
- PHP:显示sqlite数据库中的html格式数据,使用tinymce保存
- 如何自动调整标签的高度以适应内容
- Javascript高度问题
- 使用JavaScript根据窗口/视口的高度动态调整图像大小
- 用户's屏幕's高度&要保存在变量中的宽度
- 如何从加载中保存图像宽度和高度
- 在cookie中保存框架集高度并恢复下一个会话