如何在 d3 工具提示中添加点击事件



我有一个d3js条形图,如下所示。我在单击每个栏时添加工具提示。我无法添加事件来关闭提示内的工具提示。有没有办法添加它?

代码段如下所示:

var margin = {
  top: 10,
  right: 0,
  bottom: 58,
  left: 30
};
var width = 300 - margin.left - margin.right;
var height = 300 - margin.top - margin.bottom;
var barWidth = 40;
var graph;
var x;
var y;
var dataset;
var yTicks = 6;
var tooltipEl = function(d) {
  return (
    '<div class="tip__container">' +
    '<div class="val">' +
    d.val +
    "</div>" +
    '<div class="close">' +
    "<button>&times</button>" +
    "</div>" +
    "</div>"
  );
};
dataset = [{
    desc: "test1",
    val: 40
  },
  {
    desc: "some dummy text here",
    val: 120
  }
];
x = d3
  .scaleBand()
  .domain(
    dataset.map(function(d) {
      return d.desc;
    })
  )
  .range([0, width]);
y = d3
  .scaleLinear()
  .range([height, 0])
  .domain([0, 350]);
graph = d3
  .select("#graph")
  .append("svg")
  .attr("class", "bar-chart")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Tool Tip
const div = d3
  .select("#graph")
  .append("div")
  .attr("class", "tooltip")
  .style("opacity", 0);
graph
  .append("g")
  .attr("class", "x-scale")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x))
  .selectAll(".tick text")
  .call(wrap, x.bandwidth());
graph
  .append("g")
  .attr("class", "y-scale")
  .call(
    d3
    .axisLeft(y)
    .ticks(yTicks)
    .tickPadding(10)
  );
graph
  .append("g")
  .attr("class", "graph-placeholder")
  .selectAll("rect")
  .data(dataset)
  .enter()
  .append("rect")
  .attr("class", "bar1")
  .attr("height", height)
  .attr("width", barWidth)
  .attr("x", d => x(d.desc) + (x.bandwidth() - barWidth) / 2);
graph
  .append("g")
  .attr("class", "graph-main")
  .selectAll("bar1")
  .data(dataset)
  .enter()
  .append("rect")
  .attr("class", "bar2")
  .attr("x", d => x(d.desc) + (x.bandwidth() - barWidth) / 2)
  .attr("y", function(d) {
    return y(d.val);
  })
  .attr("height", function(d) {
    return height - y(d.val);
  })
  .attr("width", barWidth)
  .on("click", d => {
    div.html(tooltipEl(d));
    div
      .transition()
      .duration(200)
      .style("display", "block")
      .style("opacity", 1);
    div
      .style("left", x(d.desc) + x.bandwidth() / 2 - 1 + "px")
      .style("top", height + margin.top + 10 + "px");
  });
graph
  .append("g")
  .attr("class", "bar-label")
  .selectAll("text")
  .data(dataset)
  .enter()
  .append("text")
  .text(d => d.val + "%")
  .attr("y", function(d) {
    return y(d.val) - 5;
  })
  .attr("x", function(d) {
    return x(d.desc) + x.bandwidth() / 2;
  });
function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
      words = text
      .text()
      .split(/s+/)
      .reverse(),
      word,
      line = [],
      lineNumber = 0,
      lineHeight = 1,
      y = text.attr("y"),
      dy = parseFloat(text.attr("dy")),
      tspan = text
      .text(null)
      .append("tspan")
      .attr("x", 0)
      .attr("y", y)
      .attr("dy", dy + "em");
    while ((word = words.pop())) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text
          .append("tspan")
          .attr("x", 0)
          .attr("y", y)
          .attr("dy", ++lineNumber * lineHeight + dy + "em")
          .text(word);
      }
    }
  });
}
.bar-chart {
  background-color: #ccc;
}
.bar2 {
  fill: steelblue;
}
.bar1 {
  fill: #f2f2f2;
}
text {
  font-size: 12px;
  text-anchor: middle;
}
.bar-label text {
  text-anchor: middle;
}
path.domain {
  stroke-width: 0;
  display: none;
}
.tooltip {
  background: #FFFFFF;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.33);
  font-family: "Segoe UI";
  line-height: normal;
  padding: 15px;
  width: 100px;
  position: absolute;
  display: none;
}
.tooltip__container {
  display: flex;
}
.tooltip::before {
  content: "";
  position: absolute;
  left: 22px;
  top: -8px;
  transition: all 0.5s ease;
  border: 8px solid #fff;
  box-shadow: -5px -5px 5px rgba(0, 0, 0, 0.1);
  transform: rotate(45deg);
}
.tip__container {
  display: flex;
  justify-content: space-between;
}
.close {
  margin-left: 20px;
}
button {
  border: 1px solid #ccc;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
  <div id="graph"></div>
</div>

小提琴

因为div 的 HTML 是由柱线的 click 函数回调内的 selection.html() 方法创建的,所以您必须在同一回调中设置侦听器:

div.select("button").on("click", function() {
    div.style("opacity", 0)
});

以下是该更改的代码:

var margin = {
  top: 10,
  right: 0,
  bottom: 58,
  left: 30
};
var width = 300 - margin.left - margin.right;
var height = 300 - margin.top - margin.bottom;
var barWidth = 40;
var graph;
var x;
var y;
var dataset;
var yTicks = 6;
var tooltipEl = function(d) {
  return (
    '<div class="tip__container">' +
    '<div class="val">' +
    d.val +
    "</div>" +
    '<div class="close">' +
    "<button>&times</button>" +
    "</div>" +
    "</div>"
  );
};
dataset = [{
    desc: "test1",
    val: 40
  },
  {
    desc: "some dummy text here",
    val: 120
  }
];
x = d3
  .scaleBand()
  .domain(
    dataset.map(function(d) {
      return d.desc;
    })
  )
  .range([0, width]);
y = d3
  .scaleLinear()
  .range([height, 0])
  .domain([0, 350]);
graph = d3
  .select("#graph")
  .append("svg")
  .attr("class", "bar-chart")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Tool Tip
const div = d3
  .select("#graph")
  .append("div")
  .attr("class", "tooltip")
  .style("opacity", 0);
graph
  .append("g")
  .attr("class", "x-scale")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x))
  .selectAll(".tick text")
  .call(wrap, x.bandwidth());
graph
  .append("g")
  .attr("class", "y-scale")
  .call(
    d3
    .axisLeft(y)
    .ticks(yTicks)
    .tickPadding(10)
  );
graph
  .append("g")
  .attr("class", "graph-placeholder")
  .selectAll("rect")
  .data(dataset)
  .enter()
  .append("rect")
  .attr("class", "bar1")
  .attr("height", height)
  .attr("width", barWidth)
  .attr("x", d => x(d.desc) + (x.bandwidth() - barWidth) / 2);
graph
  .append("g")
  .attr("class", "graph-main")
  .selectAll("bar1")
  .data(dataset)
  .enter()
  .append("rect")
  .attr("class", "bar2")
  .attr("x", d => x(d.desc) + (x.bandwidth() - barWidth) / 2)
  .attr("y", function(d) {
    return y(d.val);
  })
  .attr("height", function(d) {
    return height - y(d.val);
  })
  .attr("width", barWidth)
  .on("click", d => {
    div.html(tooltipEl(d));
    div.select("button").on("click", function() {
      div.style("opacity", 0)
    });
    div
      .transition()
      .duration(200)
      .style("display", "block")
      .style("opacity", 1);
    div
      .style("left", x(d.desc) + x.bandwidth() / 2 - 1 + "px")
      .style("top", height + margin.top + 10 + "px");
  });
graph
  .append("g")
  .attr("class", "bar-label")
  .selectAll("text")
  .data(dataset)
  .enter()
  .append("text")
  .text(d => d.val + "%")
  .attr("y", function(d) {
    return y(d.val) - 5;
  })
  .attr("x", function(d) {
    return x(d.desc) + x.bandwidth() / 2;
  });
function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
      words = text
      .text()
      .split(/s+/)
      .reverse(),
      word,
      line = [],
      lineNumber = 0,
      lineHeight = 1,
      y = text.attr("y"),
      dy = parseFloat(text.attr("dy")),
      tspan = text
      .text(null)
      .append("tspan")
      .attr("x", 0)
      .attr("y", y)
      .attr("dy", dy + "em");
    while ((word = words.pop())) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text
          .append("tspan")
          .attr("x", 0)
          .attr("y", y)
          .attr("dy", ++lineNumber * lineHeight + dy + "em")
          .text(word);
      }
    }
  });
}
.bar-chart {
  background-color: #ccc;
}
.bar2 {
  fill: steelblue;
}
.bar1 {
  fill: #f2f2f2;
}
text {
  font-size: 12px;
  text-anchor: middle;
}
.bar-label text {
  text-anchor: middle;
}
path.domain {
  stroke-width: 0;
  display: none;
}
.tooltip {
  background: #FFFFFF;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.33);
  font-family: "Segoe UI";
  line-height: normal;
  padding: 15px;
  width: 100px;
  position: absolute;
  display: none;
}
.tooltip__container {
  display: flex;
}
.tooltip::before {
  content: "";
  position: absolute;
  left: 22px;
  top: -8px;
  transition: all 0.5s ease;
  border: 8px solid #fff;
  box-shadow: -5px -5px 5px rgba(0, 0, 0, 0.1);
  transform: rotate(45deg);
}
.tip__container {
  display: flex;
  justify-content: space-between;
}
.close {
  margin-left: 20px;
}
button {
  border: 1px solid #ccc;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
  <div id="graph"></div>
</div>

最新更新