簡體   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