我过去曾制作过堆叠条形图,并在鼠标悬停时添加了一些巧妙的效果。添加到这些我想改变我的用户悬停的矩形的大小,并在鼠标离开矩形后返回到默认大小。
目标是在鼠标悬停时改变矩形的大小,因此我从高度开始使用:
.on('mouseover', function(d){
d3.select(this).style("height", "110%");
} )
期望矩形的高度与其原始高度相比为 110%。遗憾的是,它无法以这种方式工作,而是获得了 div
高度的 110%。所以我尝试改用 D3 选择器:
.on('mouseover', function(d){
d3.select(this).style("height", d3.select(this).style("height")*1.10));
} )
但这也没有解决问题,使用这段代码,大小没有变化。如果我记录我正在创建的元素的高度,我的日志读取 auto
这让我相信我在获取 rect
的高度值时做错了,我应该使用什么语法?
编辑:在下面尝试 echonax 的回答,我的堆叠条形图中 rect
元素的完整代码如下:
Jaar.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); })
.style("opacity", 1)
.on('mouseover', function(d){
d.color = color(d.name);
d3.select(this).style("opacity", 1);
d3.select(this).style("height", height*1.1);
d3.select(this).style("width", width*1.1);
console.log(d3.select(this).style("width"));
tip.show(d);
} )
.on('mouseout', function(d) {
d3.select(this).style("opacity", 0.6);
d3.select(this).style("height", height);
d3.select(this).style("width", width);
tip.hide(d);
} );
最佳答案
使用
d3.select(this).attr("height", (y(d.y0) - y(d.y1))*1.1);
将大小更改为 110%
你不能做 d3.select(this).style("height")*1.10
因为 d3.select(this).style("height")
例如,是一个等于“100px”的字符串。
您可以做的是从字符串中删除“px”,乘以 1.1,然后在末尾添加“px”
var newHeight = parseInt(d3.select(this).style("height"))*1.1 + "px";
d3.select(this).style("height", newHeight);
关于javascript - 使用 D3 在鼠标悬停时更改元素大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37585842/