繁体   English   中英

在D3中的鼠标悬停时触发两个单独的事件

[英]Triggering two separate events on mouseover in D3

我有一个D3条形图,其相关数据点在每个条形上方显示为文本。 我只想在鼠标悬停时显示文本,并使条具有不同的填充颜色。 因此,从本质上讲,在鼠标悬停时,必须设置条的样式以具有不同的填充颜色,并且文本不透明度应变为1(从'0'开始)。

我在鼠标悬停上影响两个单独的事件时遇到麻烦。 我已经给两个元素都赋予了index_value属性,以便使用d3.select(this).attr(index_value)。 但是我的鼠标悬停功能不起作用。 我不知道为什么。 这是我的相关代码部分。

条形图

svg.selectAll(".bar")
    .data(data)
  .enter().append("rect")
    .attr('data-value', function(d){return d[region]})
    .attr("x", function(d) { return x(d.year); })
    .attr("width", x.rangeBand())
    .attr("y", function(d) { return y(d[region]); })
    .attr("height", function(d) { return height - y(d[region]); })
    .attr("fill", color)
    .attr("index_year", function(d, i) { return "index-" + d.year; })
    .attr("class", function(d){return "bar " + "bar-index-" + d.year;})
    .attr("color_value", color)
    .on('mouseover', synchronizedMouseOver)
    .on("mouseout", synchronizedMouseOut);

文字叠加

svg.selectAll(".bartext")
   .data(data)
   .enter()
   .append("text")
   .attr("text-anchor", "middle")
   .attr("x", function(d,i) {
        return x(d.year)+x.rangeBand()/2;
    })
    .attr("y", function(d,i) {
        return height - (height - y(d[region])) - yTextPadding;
    })
    .text(function(d){
         return d3.format(prefix)(d3.round(d[region]));
    })
    .attr("index_year", function(d, i) { return "index-" + d.year; })
    .attr("class", function(d){return "bartext " + "label-index-" + d.year;})
    .on("mouseover", synchronizedMouseOver)
    .on("mouseout", synchronizedMouseOut);

和鼠标悬停功能

var synchronizedMouseOver = function() {
      var bar = d3.select(this);
      console.log(bar);
      var indexValue = bar.attr("index_year");

      var barSelector = "." + "bar " + "bar-" + indexValue;
      var selectedBar = d3.selectAll(barSelector);
      selectedBar.style("fill", "#f7fcb9");

      var labelSelector = "." + "bartext " + "label-" + indexValue;
      var selectedLabel = d3.selectAll(labelSelector);
      selectedLabel.style("opacity", "1");

      };

这可以通过简化您的听众来实现。 您无需同时向rect和text添加侦听器。 只需将它们添加到矩形。 以下是简化的侦听器:

function synchronizedMouseOver(d) {
    var bar = d3.select(this)
        .style("fill","red");

    var text = d3.select(".label-index-" + d.year)
        .style("opacity","1");
};

function synchronizedMouseOut(d) {
    var bar = d3.select(this)
        .style("fill",color);

    var text = d3.select(".label-index-" + d.year)
        .style("opacity","0");        
};

这里的两个朋友是thisd ,分别是rect的DOM元素及其数据节点。

这里是一个FIDDLE与你的愿望的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM