d3 mouseover and click events with touch

时间:2019-01-18 18:10:59

标签: javascript d3.js

I like to use a div position:absolute as a tooltip for my d3.js charts as seen below:

<style>
  .d3-tip {
    display:inline-block;
    position: absolute;
    pointer-events:none;
  }
</style>
<body>
  <script src='https://d3js.org/d3.v5.min.js'></script>
  <script type="text/javascript">
    var tooltip = d3.select("body")
      .append("div")
      .attr("class", "d3-tip")
      .style("opacity", 0);

    var svg = d3.select("body").append("svg")
          .attr("width", 500)
          .attr("height", 800);

    svg.append("circle")
      .attr("cx", 100)
      .attr("cy", 300)
      .attr("r", 45)
      .style("fill", "gray")
      .on("mousemove", function() {
        tooltip.style("opacity", .9)
          .style("left", d3.event.pageX + 40 + "px")
          .style("top", d3.event.pageY - 40 + "px")
          .html("this is a tooltip");
      })
      .on("mouseout", function() {
        tooltip.style("opacity", 0);
      })
      .on("click", function() {
        d3.select(this).style("fill", "green");
      });
  </script>
</body>

This shows a tooltip when the cursor is over the circle, and also changes the color of the circle when it is clicked. It works with touches too (except that I can't get the tooltip to disappear, but that's another question). My problem, is that if there are any html tags in the tooltip, the touch does not seem to register as a click touchscreens.

For some reason I can't replicate this problem on codepen or jsfiddle. It works when I try it there. But here's a page with a live example that fails on my iPhone in Chrome and Safari: https://datavis.blob.core.windows.net/lmi/tooltip%20example.html

0 个答案:

没有答案