Ellipsis in the middle of a text (Mac style)

后端 未结 15 2266
长情又很酷
长情又很酷 2020-11-29 03:04

I need to implement ellipsis (\"...\") in the middle of a text within a resizable element. Here is what it might look like. So,

\"Lorem ipsum do         


        
15条回答
  •  囚心锁ツ
    2020-11-29 03:14

    None of the solutions that I saw here take into account that different characters have different width. My solution takes this into account. Basically, it strips text by one character until it fits, take a look:

    const span = document.getElementById("span");
    const div = document.getElementById("div");
    const originalText = span.textContent;
    const textLength = originalText.length;
    let part1 = originalText.substr(0, Math.floor(textLength/2));
    let part2 = originalText.substr(Math.floor(textLength/2));
    let trimPart1 = true;
    while (span.clientWidth > div.clientWidth) {
        if (trimPart1) {
        part1 = part1.substr(0, part1.length - 1);
      } else {
        part2 = part2.substr(-1 * (part2.length - 1));
      }
        span.textContent = part1 + "..." + part2;
      trimPart1 = !trimPart1;
    }
    this is a quite long text that has some words and I want it to be split in half

    https://jsfiddle.net/maxim_mazurok/oujctpz8/56/

    Mac's Finder works the same way, it first tries to strip the left part, then the right part. So, it may have WWWW...WWWWW, just as my solution.

    It's not the most efficient one though. Perhaps, the same can be achieved using virtual DOM or canvas to better optimize performance.

提交回复
热议问题