在SVG中添加省略号以溢出文本?

Ric*_*ard 26 css svg d3.js

我正在使用D3.js. 我想找到一个等同于这个CSS类的SVG,如果文本流出其包含的div,它会添加省略号:

.ai-ellipsis {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -moz-binding: url(<q>assets/xml/ellipsis.xml#ellipsis</q>);
}
Run Code Online (Sandbox Code Playgroud)

这是我的SVG:

<g class="bar" transform="translate(0,39)">
    <text class="label" x="-3" y="6.5" dy=".35em" text-anchor="start">Construction</text>    
    <rect height="13" width="123"></rect>
</g>
Run Code Online (Sandbox Code Playgroud)

它的生成如下:

barEnter.append("text").attr("class", "label")
        .attr("x", -3).attr("y", function() { return y.rangeBand() / 2})
        .attr("dy", ".35em").attr("text-anchor", "start")
        .text(function(d) {
            return d.Name;
        });
Run Code Online (Sandbox Code Playgroud)

目前,文本溢出并与rect元素重叠.

有什么方法可以说"如果文字超过一定宽度,裁剪它并添加省略号"?

use*_*569 60

溢出文本的包装函数:

    function wrap() {
        var self = d3.select(this),
            textLength = self.node().getComputedTextLength(),
            text = self.text();
        while (textLength > (width - 2 * padding) && text.length > 0) {
            text = text.slice(0, -1);
            self.text(text + '...');
            textLength = self.node().getComputedTextLength();
        }
    } 
Run Code Online (Sandbox Code Playgroud)

用法:

text.append('tspan').text(function(d) { return d.name; }).each(wrap);
Run Code Online (Sandbox Code Playgroud)

  • @patorjk这可以通过让`wrap()`返回一个函数来解决:`function wrap(width,padding){return function(){/*original function*/}}`.用法是`text.append('tspan').text(function(d){return d.name;}).each(wrap(100,5));` (5认同)
  • 很好的解决方案,我唯一的挑选是宽度和填充没有在变量部分中定义. (3认同)
  • 很好的答案.我通过使用unicode elipsis字符而不是3个点来进一步调整它.使用&hellip; 在HTML中,或在JS中\ u2026 (3认同)
  • 如果需要速度,可以使用二分搜索来确定文本的正确长度...... (2认同)

Lar*_*off 13

我不知道SVG的等效CSS类,但您可以使用foreignObject在SVG中嵌入HTML.这使您可以访问此功能,并且通常更灵活(例如,您可以轻松地自动换行).

请参阅此处以获取完整示例.

  • 仅供参考:`foreignObject`在任何版本的IE中都不起作用. (11认同)

c9s*_*c9s 5

此函数不依赖于 d3:

function textEllipsis(el, text, width) {
  if (typeof el.getSubStringLength !== "undefined") {
    el.textContent = text;
    var len = text.length;
    while (el.getSubStringLength(0, len--) > width) {
        el.textContent = text.slice(0, len) + "...";
    }
  } else if (typeof el.getComputedTextLength !== "undefined") {
    while (el.getComputedTextLength() > width) {
      text = text.slice(0,-1);
      el.textContent = text + "...";
    }
  } else {
    // the last fallback
    while (el.getBBox().width > width) {
      text = text.slice(0,-1);
      // we need to update the textContent to update the boundary width
      el.textContent = text + "...";
    }
  }
}
Run Code Online (Sandbox Code Playgroud)