为SVG中的线条添加悬停提示

3

我正在尝试为SVG中的两条线添加简单的悬停文本。在下面的代码中,我已将其包含为“title”,但当我悬停在任意一条线上时,没有任何反应。由于它们交叉,所以我并不特别在意你在交叉处悬停时会看到什么。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  <style type="text/css">
  </style>
</head>

<body>
  <script type="text/javascript">
    //Width and height
    var w = 500;
    var h = 300;
    var padding = 30;


    //Create SVG element
    var svg = d3.select("body")
      .append("svg")
      .attr("width", w)
      .attr("height", h)
      .attr("background-color", "green")

      svg.append("rect")
        .attr("width", w)
        .attr("height", h)
        .attr("fill", "green");

      svg.append("line")
        .attr("x1", 30)
        .attr("y1", 40)
        .attr("x2", 80)
        .attr("y2", 90)
        .attr("stroke", "blue")
        .attr("stroke-width", 2)
        .attr("title", "This is a blue line");

      svg.append("line")
        .attr("x1", 30)
        .attr("y1", 90)
        .attr("x2", 80)
        .attr("y2", 40)
        .attr("stroke", "red")
        .attr("stroke-width", 2)
        .attr("title", "This is a red line");

  </script>
</body>

</html>
1个回答

3

使用SVG时,您需要一个标题子元素,而不是标题属性。

  svg.append("line")
    .attr("x1", 30)
    .attr("y1", 40)
    .attr("x2", 80)
    .attr("y2", 90)
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .append("title").text("This is a blue line");

谢谢!有没有一种简单的方法让行在悬停时变得更加“突出”或“发光”?如果您认为这更合适,我也可以将其作为单独的问题发布。再次感谢。 - garson
没事了,我通过在悬停时添加不透明度类来解决了这个问题。再次感谢! - garson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接