Javascript 显示组中单个元素的工具提示

Javascript 显示组中单个元素的工具提示,javascript,d3.js,Javascript,D3.js,我有一个条形图,每个条形图的末尾都有文本值。我想做的是将文本设置为不可见,然后在mouseover上显示与该条关联的数字,大小为该条的大小。我很难想出如何有效地完成这项工作 var tooltip = d3.select("body").append("div") .style("position", "absolute") .attr("class", "tooltip") .style("opacity", 0); var rect = svg.selectAll(

我有一个条形图,每个条形图的末尾都有文本值。我想做的是将文本设置为不可见,然后在
mouseover
上显示与该条关联的数字,大小为该条的大小。我很难想出如何有效地完成这项工作

var tooltip = d3.select("body").append("div")
    .style("position", "absolute")
    .attr("class", "tooltip")
    .style("opacity", 0);

var rect = svg.selectAll("rect")
    .attr("class", "rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("y", function(d,i){
        return yScale(i);
    })
    .attr("x", 0)
    .attr("width", function(d,i){
        return xScale(d);
    })
    .attr("height", h/dataset.length)
    .style("fill", function(d,i){
        return colors(d);
    })

.on("mouseover", function(d){
    d3.select(this).style("opacity", 0.5)
    tooltip.transition()
            .duration(200)
            .style("opacity", 1);

    tooltip.html(d)
            .style("left", d3.event.pageX + "px")
            .style("top", d3.event.pageY + "px")
})

.on("mouseout", function(d){
    d3.select(this).style("opacity", 1)
    tooltip.transition()
            .duration(500)
            .style("opacity", 0)
});

我建议使用
$(此)。悬停
$(此)。mousemove
,而不是
鼠标悬停
$(此)。而不是
鼠标悬停
。试着这样做:

$(this).hover(
    function() {
        tooltip.transition()
            .duration(200)
            .style("opacity", 1)

            // In order to trigger the magnitude or 'width' of the rect:
            var rectWidth = $(this).attr("width");
    }, function () {
        tooltip.transition()
            .duration(500)
            .style("opacity", 1e-6)
    }
);

/*$(this).mousemove(function(event) {
    tooltip
        .style("left", event.clientX + "px")
        .style("top", event.clientY + "px")
});*/

您也在使用jQuery吗?那么您的代码是否适合您?我看不出它有任何效率问题?代码不起作用,缺少硬编码特定文本值,无法在单个硬编码位置显示。我希望文本值显示在每个条的长度上,无论该长度是多少。如何使用$(this)。悬停显示单个条文本值?与who文本值组相反,
dataset
是文本值组吗?它是数组还是json?它是一个由12个随机生成的数字组成的数组。如果你在问题中添加一个数组示例,并指定你想要的数字,我可以将该功能添加到我的答案中。我在我的原始帖子中添加了一张图片。我希望数字显示在它们的确切位置,但一次只能显示一个(在鼠标上)。