如何使用D3.js包装长文本标签? [英] How can I wrap long text labels with D3.js?

查看:119
本文介绍了如何使用D3.js包装长文本标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用D3创建了node-tree,并且想了解如何包装太长的文本.

I have created a node-tree using D3 and would like to understand how to wrap texts that are too long.

  nodeUpdate.select("text")
      .text(function(d) {
        if(d.name == "root"){
            return "";
        } else {
            return d.name;
        }
       })
      .style("font-family", "Verdana")
      .style("fill-opacity", 1);

如果d.name太长,我希望它填充几行而不是一行.我已经找到了 http://bl.ocks.org/mbostock/7555321 ,但我确实似乎不了解它是如何工作的,我当然也不了解换行"功能是如何获取输入的?在此示例中,wrap函数在调用时没有参数.

If d.name is too long I'd like it to fill several lines instead of one. I have found this http://bl.ocks.org/mbostock/7555321 but I do not seem to understand how this works, and I certainly don't understand how the "wrap" function gets it's input? On this example the wrap function has no parameters when called.

推荐答案

来自http://bl .ocks.org/mbostock/7555321 有两个关键部分.

wrap()的调用已完成

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
.selectAll(".tick text")
  .call(wrap, x.rangeBand());

期望文本元素和宽度类似

which is expecting a text element and a width like done in

node.append("text")
  // Make sure to have a text element
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 50);

这里令人困惑的部分是,调用语句适用于当前选择,例如.tick text或所有节点.

The confusing part here is that call statements apply to the current selection like .tick text or all nodes.

第二部分是必需的text.text(),否则它将不起作用.

The second part is the required text.text() otherwise it does not work.

function wrap(text, width) {
  text.each(function() {
  var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),

这篇关于如何使用D3.js包装长文本标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆