javascript - 图例没有附加到 div 中,而是打印在 div 之外

标签 javascript css d3.js

<!DOCTYPE html>
<html>

<head>

  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Testing Donut Chart</title>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

  <style type="text/css">
    #first {
      /*    width: 500px;
    height: 300px;*/
      height: 50%;
      width: 50%;
      border: 3px solid #73AD21;
      position: absolute;
    }
    #chart {
      position: absolute;
      height: 100%;
      width: 100%;
    }
    #chart legend {
      position: absolute;
      margin: 0%;
    }
    #first legend {
      position: absolute;
      margin: 0%;
    }
    .slice path {
      stroke: #fff;
      stroke-width: 1px;
    }
    .textTop {
      font-family: 'Segoe UI';
      font-weight: bold;
      font-size: 10pt;
      fill: #2c3218;
    }
    .textBottom {
      fill: #444;
      font-family: 'Segoe UI';
      font-weight: bold;
      font-size: 10pt;
    }
  </style>
</head>

<body>
  <div id="container">
    <svg id="chart" viewBox="0 0 960 500" perserveAspectRatio="xMinYMid">
      <div id="first">
        <script type="text/javascript">
          var w = document.getElementById('first').clientWidth;
           // alert(w);
          var h = document.getElementById('first').clientHeight;
           // alert(h);
          var r = Math.min(w, h) / 2 - 50;
           // alert(r);
          var inner = 70;
          var color = d3.scale.category10();

          var data = [
            ["192.168.12.1", 20],
            ["76.09.45.34", 40],
            ["34.91.23.76", 80],
            ["192.168.19.32", 16],
            ["192.168.10.89", 50],
            ["192.178.34.07", 18],
            ["192.168.12.98", 30]
          ];

          var data = data.map(function(d) {
            return {
              IP: d[0],
              count: d[1]
            };
          });

          var total = d3.sum(data, function(d) {
            return d3.sum(d3.values(d));
          });

          var vis = d3.select("#first")
            .append("svg:svg")
            .data([data])
            .attr("width", w)
            .attr("height", h)
            .append("svg:g")
            .attr("transform", "translate(" + r * 1.5 + "," + r * 1.5 + ")");

          var textTop = vis.append("text")
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .attr("class", "textTop")
            .text("TOTAL")
            .attr("y", -10),

            textBottom = vis.append("text")
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .attr("class", "textBottom")
            .text(total)
            .attr("y", 10);

          var arc = d3.svg.arc()
            .innerRadius(inner)
            .outerRadius(r);

          var arcOver = d3.svg.arc()
            .innerRadius(inner + 0)
            .outerRadius(r + 1);

          var pie = d3.layout.pie()
            .sort(null)
            .startAngle(1.1 * Math.PI)
            .endAngle(3.1 * Math.PI)
            .value(function(d) {
              return d.count;
            });

          var arcs = vis.selectAll("g.slice")
            .data(pie)
            .enter()
            .append("svg:g")
            .attr("class", "slice")
            .on("mouseover", function(d) {
              d3.select(this).select("path").transition()
                .duration(200)
                .attr("d", arcOver)
                .style('opacity', 0.5)

              textTop.text(d3.select(this).datum().data.IP)
                .attr("y", -10);
              textBottom.text(d3.select(this).datum().data.count)
                .attr("y", 10);
            })
            .on("mouseout", function(d) {
              d3.select(this).select("path").transition()
                .duration(100)
                .attr("d", arc)
                .style('opacity', 1);

              textTop.text("TOTAL")
                .attr("y", -10);
              textBottom.text(total);
            });

          arcs.append("svg:path")
            .attr("fill", function(d, i) {
              return color(i);
            })
            .attr("d", arc)
            .transition()
            .ease("exp")
            .duration(1000)
            .attrTween("d", tweenPie);

          function tweenPie(b) {
            var i = d3.interpolate({
              startAngle: 1.1 * Math.PI,
              endAngle: 1.1 * Math.PI
            }, b);
            return function(t) {
              return arc(i(t));
            };
          }

          var legend = d3.select("#first")
            .append("svg")
            .attr("x", w)
            .attr("y", h)
            .attr("class", "legend")
            .attr("width", w / 2)
            .attr("height", h)
            .selectAll("g")
            .data(data)
            .enter()
            .append("g")
            .attr("transform", function(d, i) {
              return "translate(0," + i * 20 + ")";
            });

          legend.append("rect")
            .attr("width", 18)
            .attr("height", 18)
            .style("fill", function(d, i) {
              return color(i);
            });

          legend.append("text")
            .attr("x", 24)
            .attr("y", 9)
            .attr("dy", ".35em")
            .text(function(d) {
              return d.IP;
            });
        </script>
      </div>
    </svg>
  </div>

  <script type="text/javascript">
    var chart = $("#chart"),
      aspect = chart.width() / chart.height(),
      container = chart.parent();
    $(window).on("resize", function() {
      var targetWidth = container.width();
      chart.attr("width", targetWidth);
      chart.attr("height", Math.round(targetWidth / aspect));
    }).trigger("resize");
  </script>

</body>

</html>

我已经尝试了很多,但我无法在 div #first 中正确显示 donut 和图例。我试图改变很多事情,但没有任何效果。这是我尝试使用 d3 做的不可能的事情,还是我正在做的任何特定错误。此外,div 和图表也没有响应。我很困惑。请任何人帮助我。 在此先感谢您的帮助。

最佳答案

您为图例和图片图使用了单独的 SVG。我将图例附加到以前使用的 SVG 中并对其位置进行转换。

下面的代码片段可能对您有所帮助。

<!DOCTYPE html>
<html>

<head>

  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Testing Donut Chart</title>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

  <style type="text/css">
    #first {
      /*    width: 500px;
    height: 300px;*/
      height: 95% !important;
      width: 95% !important;
      border: 3px solid #73AD21 !important;
      position: absolute !important;
    }
    #chart {
      position: absolute;
      height: 100%;
      width: 100%;
    }
    #chart legend {
      position: absolute;
      margin: 0%;
    }
    #first legend {
      position: absolute;
      margin: 0%;
    }
    .slice path {
      stroke: #fff;
      stroke-width: 1px;
    }
    .textTop {
      font-family: 'Segoe UI';
      font-weight: bold;
      font-size: 10pt;
      fill: #2c3218;
    }
    .textBottom {
      fill: #444;
      font-family: 'Segoe UI';
      font-weight: bold;
      font-size: 10pt;
    }
  </style>
</head>

<body>
  <div id="container">
    <svg id="chart" viewBox="0 0 960 500" perserveAspectRatio="xMinYMid">
      <div id="first">
        <script type="text/javascript">
          var w = document.getElementById('first').clientWidth;
           // alert(w);
          var h = document.getElementById('first').clientHeight;
           // alert(h);
          var r = Math.min(w, h) / 2 - 50;
           // alert(r);
          var inner = 70;
          var color = d3.scale.category10();

          var data = [
            ["192.168.12.1", 20],
            ["76.09.45.34", 40],
            ["34.91.23.76", 80],
            ["192.168.19.32", 16],
            ["192.168.10.89", 50],
            ["192.178.34.07", 18],
            ["192.168.12.98", 30]
          ];

          var data = data.map(function(d) {
            return {
              IP: d[0],
              count: d[1]
            };
          });

          var total = d3.sum(data, function(d) {
            return d3.sum(d3.values(d));
          });

          var vis = d3.select("#first")
            .append("svg:svg")
            .data([data])
            .attr("width", w)
            .attr("height", h)
            .append("svg:g")
            .attr("transform", "translate(" + r * 1.5 + "," + r * 1.5 + ")");

          var textTop = vis.append("text")
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .attr("class", "textTop")
            .text("TOTAL")
            .attr("y", -10),

            textBottom = vis.append("text")
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .attr("class", "textBottom")
            .text(total)
            .attr("y", 10);

          var arc = d3.svg.arc()
            .innerRadius(inner)
            .outerRadius(r);

          var arcOver = d3.svg.arc()
            .innerRadius(inner + 0)
            .outerRadius(r + 1);

          var pie = d3.layout.pie()
            .sort(null)
            .startAngle(1.1 * Math.PI)
            .endAngle(3.1 * Math.PI)
            .value(function(d) {
              return d.count;
            });

          var arcs = vis.selectAll("g.slice")
            .data(pie)
            .enter()
            .append("svg:g")
            .attr("class", "slice")
            .on("mouseover", function(d) {
              d3.select(this).select("path").transition()
                .duration(200)
                .attr("d", arcOver)
                .style('opacity', 0.5)

              textTop.text(d3.select(this).datum().data.IP)
                .attr("y", -10);
              textBottom.text(d3.select(this).datum().data.count)
                .attr("y", 10);
            })
            .on("mouseout", function(d) {
              d3.select(this).select("path").transition()
                .duration(100)
                .attr("d", arc)
                .style('opacity', 1);

              textTop.text("TOTAL")
                .attr("y", -10);
              textBottom.text(total);
            });

          arcs.append("svg:path")
            .attr("fill", function(d, i) {
              return color(i);
            })
            .attr("d", arc)
            .transition()
            .ease("exp")
            .duration(1000)
            .attrTween("d", tweenPie);

          function tweenPie(b) {
            var i = d3.interpolate({
              startAngle: 1.1 * Math.PI,
              endAngle: 1.1 * Math.PI
            }, b);
            return function(t) {
              return arc(i(t));
            };
          }

          var legend = vis.append("g")
            /*.attr("id", "first")
            .append("g")*/
            .attr("transform", "translate("+w / 3+", -"+ h/4 +")")
            .attr("class", "legend")
            .attr("width", w / 2)
            .attr("height", h)
            .selectAll("g")
            .data(data)
            .enter()
            .append("g")
            .attr("transform", function(d, i) {
              return "translate(0," + i * 20 + ")";
            });

          legend.append("rect")
            .attr("width", 18)
            .attr("height", 18)
            .style("fill", function(d, i) {
              return color(i);
            });

          legend.append("text")
            .attr("x", 24)
            .attr("y", 9)
            .attr("dy", ".35em")
            .text(function(d) {
              return d.IP;
            });
        </script>
      </div>
    </svg>
  </div>

  <script type="text/javascript">
    var chart = $("#chart"),
      aspect = chart.width() / chart.height(),
      container = chart.parent();
    $(window).on("resize", function() {
      var targetWidth = container.width();
      chart.attr("width", targetWidth);
      chart.attr("height", Math.round(targetWidth / aspect));
    }).trigger("resize");
  </script>

</body>

</html>

关于javascript - 图例没有附加到 div 中,而是打印在 div 之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37983126/

相关文章:

jquery - 在 Windows Phone 8 上的 IE 10 上滚动时网页闪烁

javascript - 为什么我一直收到 "Cannot call method ' addEventListener' of null”?

javascript - 如何复制 SVG 的内容并将其附加到另一个 SVG 框架?

javascript - d3 csv 读入数组中的对象

javascript - SailsJS 使用自定义 EJS 过滤器

html - 如何让 HTML 元素变大?

javascript - D3 : how to select the div from multiple divs with the same class by the inner html in D3?

javascript - D3.js 在鼠标悬停时更改文本,这可能吗?

javascript - 将处理转换为 p5.js

javascript - 如何在json文件中添加或插入记录