这是我的js代码。单击矩形时,我必须调整宽度和高度。例如,假设树形图中有五个矩形,如果我单击一个矩形意味着我将调整整个宽度和高度,我也必须调整文本。
<script src="/js/jquery.min.js"></script>
<script src="/js/d3.v3.min.js"></script>
<script>
function transformrect(from, to) {
/* Returns the transform="" attribute to resize from rectangle to to rectangle */
var x, y,
xscale = to.width / from.width,
yscale = to.height / from.height;
if (xscale >= yscale) {
x = (to.x + to.width / 2) / yscale - (from.x + from.width / 2);
y = to.y / yscale - from.y;
scale = yscale;
} else {
y = (to.y + to.height / 2) / xscale - (from.y + from.height / 2);
x = to.x / xscale - from.x;
scale = xscale;
}
return 'scale(' + scale + ')translate(' + x + ',' + y + ')';
}
var root = {x:10, y:10, width:1150, height:400};
d3.selectAll('.l0').on('click', function() {
var transform = transformrect(d3.select(this).select('rect').node().getBBox(), root);
d3.selectAll('.zoommap rect, .zoommap text')
.transition()
.duration(500)
.attr('transform', transform);
d3.select(this).style('display', 'none');
});
d3.selectAll('.l1').on('click', function() {
var transform = transformrect(d3.select(this).select('rect').node().getBBox(), root);
d3.selectAll('.zoommap rect, .zoommap text')
.transition()
.duration(500)
.attr('transform', transform);
d3.select(this).style('display', 'none');
});
d3.selectAll('.l2').on('click', function() {
var transform = transformrect(d3.select(this).select('rect').node().getBBox(), root);
d3.selectAll('.zoommap rect, .zoommap text')
.transition()
.duration(500)
.attr('transform', transform);
d3.select(this).style('display', 'none');
});
d3.selectAll('.l3 rect').on('click', function() {
d3.selectAll('.zoommap rect, .zoommap text')
.transition()
.duration(500)
.attr('transform', 'scale(1)translate(0,0)')
.each('end', function() {
d3.selectAll('.l0').style('display', undefined);
});
})
</script>
&#13;
答案 0 :(得分:1)
这样的事情应该做:
d3.select('rect').on('click',function(d){
d3.select(this)
.attr('width', changeWidthHere)
.attr('height', changeHeightHere)
.text(changeTextHere);
}
var svg = d3.select('body').append('svg').attr('width', 500).attr('height', 500);
var data = [{
value : 1,
text : 'One'
},
{
value : 2,
text : 'Two'
},
{
value : 3,
text : 'Three'
}]
svg.selectAll('rect')
.data(data)
.enter().append('rect')
.attr('x', function(d,i) { d.clicked=false; return 100+100*i; })
.attr('y', function(d,i) { return 0; })
.attr('width', function() { return 60; })
.attr('height', function() { return 60; })
.attr('fill', function() { return 'red'; })
.on('click',function(d){
d3.select(this)
.attr('width', function(f){ return f.clicked ? 60 : 20})
.attr('height', function(f){ return f.clicked ? 60 : 20})
.each(function(d){ console.log(d.clicked);d.clicked = !d.clicked})
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;