kar*_*tos 7 javascript svg attributes d3.js
我正在为SVG-G元素(SVG组对象)分配人工属性.我使用SVG转换的内容移动组,并将组的x/y坐标及其宽度/高度存储在这些属性中.
我正在使用D3 Javascript库和调用:
embeddedElemContainer = nodeBoxContainer.append('svg:g')
.attr('x', x)
.attr('y', y)
.attr('width', width)
.attr('height', height)
Run Code Online (Sandbox Code Playgroud)
结果如下:
<g transform="translate(13.585786437626904,31.585786437626904)" x="13.585786437626904" y="31.585786437626904" width="43.00000000000001" height="0"></g>
Run Code Online (Sandbox Code Playgroud)
这是好的,唯一困扰我的事实是,属性值存储为字符串.如果我想用它们进行一些计算,我不得不施展.
parseInt(@embeddedElemContainer.attr('x'))
Run Code Online (Sandbox Code Playgroud)
有没有办法将这些值直接存储为整数/双?
D3中的常规方法是拥有绑定到节点的数据列表.请参阅Selection API的数据部分.D3将其置于__data__它创建/修改的DOM节点的属性中.在内部D3拉出该属性并将其作为参数传递给各种函数,但您当然可以直接自己访问它.
也可以通过Datum方法将任意数据结构与单个节点相关联.
没有其他上下文,很难说,但下面是我认为你想要做的修改版本:
var vis = d3.select("body").append("svg").attr("width", 400).attr("height", 300);
var groupData = {x: 100, y:100, height: 50, width: 50, theanswer : 42, thecolor: "blue", somedouble: 45.1651654 };
var embeddedElemContainer = vis.append('svg:g')
.datum( groupData )
.attr( 'id', 'mygroup' )
.attr( 'x', function(d) { return d.x; } )
.attr( 'y', function(d) { return d.y; } )
.attr( 'height', function(d) { return d.height; } )
.attr( 'width', function(d) { return d.width; } )
// the regular DOM way:
console.log(document.getElementById('mygroup').__data__)
// the D3 way:
console.log( d3.select('#mygroup').datum() );
Run Code Online (Sandbox Code Playgroud)
两个console.log语句输出:
height: 50
somedouble: 45.1651654
theanswer: 42
thecolor: "blue"
width: 50
x: 100
y: 100
Run Code Online (Sandbox Code Playgroud)