javascript - SVG 元素 — 处理和选择文本

标签 javascript d3.js svg

在解决 d3 中的问题时遇到问题 - 我正在尝试将图例附加到我的 svg,并且我放入其中的文本需要分开,因此只有 d.key 由 colorScale 和d.total 位于 d.key 下方,填充为“黑色”。

这是我刚才提到的代码行 - .text(function(d) { return (d.key) + ' (' + d.total + ')'; })

简而言之,如何在 d.key 下面添加另一行文本并使该新文本的填充为“黑色”,或者只是不像 d.key 那样使用 colorScale 着色。

svg.append("g")
        .attr("class", "legend")
          .selectAll("text")
          .data(layers)
            .enter().append("text")
              .text(function(d) { return (d.key) + ' (' + d.total + ')'; })
              .attr('fill', function(d) { return colorScale(d.key); })
              .attr('y', function(d, i) { return 50 * (i + 2.75); })
              .attr('x', "375");

最佳答案

有多种方法可以做到这一点。两个独立的 text 元素包裹在 g 中,或者我下面显示的是两个 tspan 包裹在 text 中:

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

var layers = [
  {
    key: 'one',
    total: 10
  }, {
    key: 'two',
    total: 20
  }
];

var colorScale = d3.scale.category10();

var text = svg.append("g")
  .attr("class", "legend")
  .selectAll("text")
  .data(layers)
  .enter().append("text")
  .attr('y', function(d, i) { return 50 * (i + 2.75); })

text.append("tspan")
  .text(function(d) { return (d.key) + ' (' + d.total + ')'; })
  .attr('fill', function(d) { return colorScale(d.key); })  
  .attr('x', "375");

text.append("tspan")
  .attr("dy", "1.2em")
  .attr("x", "375")
  .text("Second row of text")
  .style("fill", "black");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

关于javascript - SVG 元素 — 处理和选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170030/

相关文章:

javascript - 使用 jQuery 将两个 div 合并到一个 .html 中

javascript - 检查我的输入框是否被点击或者是 'in focus'纯js

html - 如何在 SVG 文档中显示 HTML?

javascript - 在 SVG 中创建可变渐变

javascript - MVC4 中的 Kendo UI 网格单元格着色

javascript - 从 JSON 中获取特定元素

javascript - 如何更改 D3.js 中的最后一个刻度值?

javascript - 如何根据用户偏好过滤通过 d3.js 渲染的节点和边?

javascript - OpenSeaDragon 与 D3 svg-overlay 可拖动元素

c++ - 资助 MathML 渲染库