Add ellipses to overflowing text in SVG?

前端 未结 6 1057
广开言路
广开言路 2020-11-30 03:20

I\'m using D3.js. I\'d like to find an SVG equivalent to this CSS class, which adds ellipses if text flows out of its containing div:



        
6条回答
  •  天命终不由人
    2020-11-30 03:49

    This function does not depend on 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 + "...";
        }
      }
    }
    

提交回复
热议问题