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

新手上路,请多包涵

我正在使用 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>);
}

这是我的 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>

它的生成如下:

 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;
        });

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

有什么办法可以说“如果文本超过一定宽度,裁剪它并添加椭圆”?

原文由 Richard 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

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

有关完整示例,请参见 此处

原文由 Lars Kotthoff 发布,翻译遵循 CC BY-SA 3.0 许可协议

Mauro Colella 在打字稿中的出色回答:

 export const svgTextEllipsis = (textNode: SVGTextElement, padding = 0) => {
  const d3Node = d3.select(textNode);
  const targetWidth = Number(d3Node.attr("width")) - padding;
  const initialText = d3Node.text();
  const precision = 25;
  const maxIterations = 3;

  let textWidth = d3Node.node()?.getComputedTextLength() ?? 0;
  let textLength = initialText.length;
  let text = initialText;
  let i = 0;

  if (textWidth < targetWidth) return;

  while (
    i < maxIterations &&
    text.length > 0 &&
    Math.abs(targetWidth - textWidth) > precision
  ) {
    text =
      textWidth >= targetWidth
        ? text.slice(0, -textLength * 0.15)
        : initialText.slice(0, textLength * 1.15);
    d3Node.text(`${text}…`);
    textWidth = d3Node.node()?.getComputedTextLength() ?? 0;
    textLength = text.length;
    i += 1;
  }

  d3Node.text(d3Node.text().replace(/…+/, "…"));
};

原文由 Flonk 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题