将省略号应用于多行文本

时间:2015-10-10 19:18:59

标签: html css css3 ellipsis

是否有解决方案在div中具有流体高度(20%)的最后一行添加省略号?

我在CSS中找到了-webkit-line-clamp函数,但在我的情况下,行号将取决于窗口大小。



p {
    width:100%;
    height:20%;
    background:red;
    position:absolute;
}

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>
&#13;
&#13;
&#13;

我有这个JSFiddle来说明这个问题。 https://jsfiddle.net/96knodm6/

25 个答案:

答案 0 :(得分:82)

如果要将省略号(...)应用于单行文本,CSS使用text-overflow属性可以轻松实现。它仍然有点棘手(由于所有要求 - 见下文),但text-overflow使其成为可能和可靠。

但是,如果你想在多行文字上使用省略号 - 就像这里的情况那样 - 那么不要期望有任何乐趣。 CSS没有标准的方法来执行此操作,并且解决方法很容易被击中。

单行文本的省略号

使用text-overflow,省略号可以应用于单行文本。必须满足以下CSS要求:

  • 必须有widthmax-widthflex-basis
  • 必须有white-space: nowrap
  • 必须overflow的值不是visible
  • 必须为display: blockinline-block (或功能等同物,例如弹性物品)。

所以这会奏效:

p {
  width: 200px;
  white-space: nowrap;
  overflow: hidden;
  display: inline-block;
  text-overflow: ellipsis;
  border: 1px solid #ddd;
  margin: 0;
}
<p>
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>.
  This is a test of CSS <i>text-overflow: ellipsis</i>.
  This is a test of CSS <i>text-overflow: ellipsis</i>.
</p>

jsFiddle version

但是,请尝试删除width,或将overflow默认设置为visible,或删除white-space: nowrap,或使用块容器元素以外的其他内容,AND,省略号失败了。

这里有一个重要的要点: text-overflow: ellipsis对多行文字没有影响。 (仅white-space: nowrap要求就消除了这种可能性。)

p {
    width: 200px;
    /* white-space: nowrap; */
    height: 90px; /* new */
    overflow: hidden;
    display: inline-block;
    text-overflow: ellipsis;
    border: 1px solid #ddd;
    margin: 0;
}
<p>
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>. 
  This is a test of CSS <i>text-overflow: ellipsis</i>.
  This is a test of CSS <i>text-overflow: ellipsis</i>.
  This is a test of CSS <i>text-overflow: ellipsis</i>.
</p>

jsFiddle version

多行文字的省略号

由于CSS在多行文本上没有省略号的属性,因此创建了各种变通方法。其中有几种方法可以在这里找到:

上面的Mobify链接已损坏,但似乎已在this codepen中实施。

答案 1 :(得分:28)

请检查此css以获取省略号到多行文字

&#13;
&#13;
body {
  margin: 0;
  padding: 50px;
}

/* mixin for multiline */
.block-with-text {
  overflow: hidden;
  position: relative;
  line-height: 1.2em;
  max-height: 6em;
  text-align: justify;
  margin-right: -1em;
  padding-right: 1em;
}
.block-with-text:before {
  content: '...';
  position: absolute;
  right: 0;
  bottom: 0;
}
.block-with-text:after {
  content: '';
  position: absolute;
  right: 0;
  width: 1em;
  height: 1em;
  margin-top: 0.2em;
  background: white;
}
&#13;
<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of  Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon;  use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>
&#13;
&#13;
&#13;

答案 2 :(得分:11)

我终于找到了做我想要的解决方案。 作为p一个paragraphe和article包装器。 如果您要根据p高度(也取决于窗口高度)将省略号应用于article,则需要获取height article,{line-height 1}} {} {},然后p找到可以动态添加的articleHeight/lineHeight的数量。

唯一的问题是应该在css文件中声明line-clamp

检查以下代码。如果更改窗口的高度,line-height将会更改。可以很好地创建一个旨在实现这一目标的插件。

jsfiddle

&#13;
&#13;
line-clamp
&#13;
function lineclamp() {
  var lineheight = parseFloat($('p').css('line-height'));
  var articleheight = $('article').height(); 
  var calc = parseInt(articleheight/lineheight);
  $("p").css({"-webkit-line-clamp": "" + calc + ""});
}


$(document).ready(function() {
    lineclamp();
});

$( window ).resize(function() {
 	lineclamp();
});
&#13;
article {
  height:60%;
  background:red;
  position:absolute;
}

p {
  margin:0;
  line-height:120%;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
&#13;
&#13;
&#13;

答案 3 :(得分:9)

只需增加 -webkit-line-clamp:4; 即可增加行数

&#13;
&#13;
p {
    display: block;
    display: -webkit-box;
    max-width: 200px;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
&#13;
<p>Lorem ipsum dolor sit amet, novum menandri adversarium ad vim, ad his persius nostrud conclusionemque. Ne qui atomorum pericula honestatis. Te usu quaeque detracto, idque nulla pro ne, ponderum invidunt eu duo. Vel velit tincidunt in, nulla bonorum id eam, vix ad fastidii consequat definitionem.</p>
&#13;
&#13;
&#13;

编辑02/05/2018

线夹是一种专有的,未记录的CSS(webkit):https://caniuse.com/#feat=css-line-clamp,所以它目前仅适用于少数浏览器。

答案 4 :(得分:7)

我刚刚用这个概念玩了一下。基本上,如果你可能有一个像素左右切断你的最后一个字符,这里是一个纯粹的CSS和HTML解决方案:

这种方法的工作方式是将div绝对定位在视口的可视区域下方。随着内容的增长,我们希望div可以偏移到可见区域。如果内容增长太多,我们的div将偏移得太高,因此我们的内容可以增长的上限。

HTML:

<div class="text-container">
  <span class="text-content">
    PUT YOUR TEXT HERE
    <div class="ellipsis">...</div> // You could even make this a pseudo-element
  </span>
</div>

CSS:

.text-container {
    position: relative;
    display: block;
    color: #838485;
    width: 24em;
    height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
    overflow: hidden;
    white-space: normal;
}

.text-content {
  word-break: break-all;
  position: relative;
  display: block;
  max-height: 3em;       // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport 
}

.ellipsis {
  position: absolute;
  right: 0;
  top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
  text-align: left;
  background: white;
}

我在Chrome,FF,Safari和IE 11中对此进行了测试。

您可以在此处查看:http://codepen.io/puopg/pen/vKWJwK

你甚至可以通过一些CSS魔法减轻角色的突然切断。

编辑:我想这有一个问题就是分词:break-all,否则内容不会延伸到视口的最后。 :(

答案 5 :(得分:7)

man有最佳解决方案。只有css:

.multiline-ellipsis {
    display: block;
    display: -webkit-box;
    max-width: 400px;
    height: 109.2px;
    margin: 0 auto;
    font-size: 26px;
    line-height: 1.4;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

答案 6 :(得分:6)

不幸的是没有CSS当前的事态。

省略号渲染具有先决条件white-space:nowrap,实际上意味着:省略号仅在单行文本容器上绘制。

答案 7 :(得分:6)

用户使用此公式:

overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2; //put number of line here

答案 8 :(得分:3)

我查看了YouTube如何在其主页上解决该问题并对其进行了简化:

.multine-ellipsis {
  -webkit-box-orient: vertical;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}

这将允许两行代码,然后附加省略号。

要点:https://gist.github.com/eddybrando/386d3350c0b794ea87a2082bf4ab014b

答案 9 :(得分:2)

p {
    width:100%;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    background:#fff;
    position:absolute;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>

答案 10 :(得分:2)

可能这可以帮助你们。带有工具提示悬停的多行椭圆。 https://codepen.io/Anugraha123/pen/WOBdOb

<div>
     <p class="cards-values">Lorem ipsum dolor sit amet,   consectetur adipiscing elit. Nunc aliquet lorem commodo, semper mauris nec, suscipit nisi. Nullam laoreet massa sit amet leo malesuada imperdiet eu a augue. Sed ac diam quis ante congue volutpat non vitae sem. Vivamus a felis id dui aliquam tempus
      </p>
      <span class="tooltip"></span>
</div>

答案 11 :(得分:2)

我想出了我自己的解决方案:

/*this JS code puts the ellipsis (...) at the end of multiline ellipsis elements
 *
 * to use the multiline ellipsis on an element give it the following CSS properties
 * line-height:xxx
 * height:xxx (must line-height * number of wanted lines)
 * overflow:hidden
 *
 * and have the class js_ellipsis
 * */

//do all ellipsis when jQuery loads
jQuery(document).ready(function($) {put_ellipsisses();});

//redo ellipsis when window resizes
var re_ellipsis_timeout;
jQuery( window ).resize(function() {
    //timeout mechanism prevents from chain calling the function on resize
    clearTimeout(re_ellipsis_timeout);
    re_ellipsis_timeout = setTimeout(function(){ console.log("re_ellipsis_timeout finishes"); put_ellipsisses(); }, 500);
});

//the main function
function put_ellipsisses(){
    jQuery(".js_ellipsis").each(function(){

        //remember initial text to be able to regrow when space increases
        var object_data=jQuery(this).data();
        if(typeof object_data.oldtext != "undefined"){
            jQuery(this).text(object_data.oldtext);
        }else{
            object_data.oldtext = jQuery(this).text();
            jQuery(this).data(object_data);
        }

        //truncate and ellipsis
        var clientHeight = this.clientHeight;
        var maxturns=100; var countturns=0;
        while (this.scrollHeight > clientHeight && countturns < maxturns) {
            countturns++;
            jQuery(this).text(function (index, text) {
                return text.replace(/\W*\s(\S)*$/, '...');
            });
        }
    });
}

答案 12 :(得分:1)

int getEtudiants(FILE *fe, int *num, char nom[100][30],char pre[100][30],char sec[100][10]) {
    FILE *p;
    p = fe;
    fseek(p, 0, SEEK_SET);
    //char temp[5] = {0};
    char *temp = (char*)malloc(sizeof(char) * 75);
    int i = 0;
    int lines = 0;
    int ch;
    int n = 0;

    while((ch = getc(p)) != EOF) {
        if(ch == '\n') lines++;
    }
    fseek(p, 0, SEEK_SET);
    //printf("found %d students\n", lines);
    char *lineBuffer = (char*)malloc(sizeof(char) * 75);

    for(i = 0; i < lines; i++){                   
        fgets(lineBuffer, 76, p); 
        strncpy(temp, lineBuffer, 5);
        num[i] = atoi(temp);
        strncpy(nom[i], lineBuffer + 5, 30);
        trimStr(nom[i]);
        strncpy(pre[i], lineBuffer + 35, 30);
        trimStr(pre[i]);
        strncpy(sec[i], lineBuffer + 65,10);
        trimStr(sec[i]);
        //printf("num: %d,%s %s section: %s\n", num[i], nom[i], pre[i], sec[i]);
        fseek(p, 2, SEEK_CUR);
        n++;
    }
    return n;
}

答案 13 :(得分:1)

base64

答案 14 :(得分:1)

请检查以下代码,以确保具有正确对齐的纯CSS技巧,并支持所有浏览器

 .block-with-text {
    overflow: hidden;
    position: relative;
    line-height: 1.2em;
    max-height: 103px;
    text-align: justify;
    padding: 15px;
}

.block-with-text:after {
    content: '...';
    position: absolute;
    right: 15px;
    bottom: -4px;
    background: linear-gradient(to right, #fffff2, #fff, #fff, #fff);
}

<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon; use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>

答案 15 :(得分:1)

经过多次尝试,我最终得到了一个混合的js / css来处理多行和单行溢出。

CSS3代码:

.forcewrap { // single line ellipsis
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  overflow: hidden;
  -moz-binding: url( 'bindings.xml#ellipsis' );
  white-space: nowrap;
  display: block;
  max-width: 95%; // spare space for ellipsis
}

.forcewrap.multiline {
  line-height: 1.2em;  // my line spacing 
  max-height: 3.6em;   // 3 lines
  white-space: normal;
}

.manual-ellipsis:after {
  content: "\02026";      // '...'
  position: absolute;     // parent container must be position: relative
  right: 10px;            // typical padding around my text
  bottom: 10px;           // same reason as above
  padding-left: 5px;      // spare some space before ellipsis
  background-color: #fff; // hide text behind
}

我只是用js代码检查div上的溢出,如下所示:

function handleMultilineOverflow(div) {
    // get actual element that is overflowing, an anchor 'a' in my case
    var element = $(div).find('a'); 
    // don't know why but must get scrollHeight by jquery for anchors
    if ($(element).innerHeight() < $(element).prop('scrollHeight')) {
        $(element).addClass('manual-ellipsis');
    }
}

html中的用法示例:

<div class="towrap">
  <h4>
    <a class="forcewrap multiline" href="/some/ref">Very long text</a>
  </h4>
</div>

答案 16 :(得分:0)

对于不好的CSS不支持跨浏览器多行钳位,只有webkit似乎在推动它。

您可以尝试在github上使用像Ellipsity这样的简单Javascript省略库,源代码非常干净小,所以如果您需要进行任何其他更改,它应该非常简单。

https://github.com/Xela101/Ellipsity

答案 17 :(得分:0)

在浏览了整个互联网并尝试了很多这些选项后,确保通过javascript支持正确覆盖的唯一方法就是通过javascript,我创建了一个循环函数来检查需要多行的帖子项目截断。

*注意我使用了Jquery,并要求你的post__items类具有固定的最大高度。

// loop over post items
$('.post__items').each(function(){
    var textArray = $(this).text().split(' ');
    while($(this).prop('scrollHeight') > $(this).prop('offsetHeight')) {
        textArray.pop();
        $(this).text(textArray.join(' ') + '...');
     }
});

答案 18 :(得分:0)

p{
line-height: 20px;
width: 157px;
white-space: nowrap; 
overflow: hidden;
text-overflow: ellipsis;
}

或者我们可以通过使用和高度和溢出限制行。

答案 19 :(得分:0)

适用于多行省略号的我的解决方案:

.crd-para {
    color: $txt-clr-main;
    line-height: 2rem;
    font-weight: 600;
    margin-bottom: 1rem !important;
    overflow: hidden;

    span::after {
        content: "...";
        padding-left: 0.125rem;
    }
}

答案 20 :(得分:0)

你可以在CSS3中使用线钳功能。

p {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-height: 25px;
    height: 52px;
    max-height: 52px;
    font-size: 22px;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

请务必更改您拥有的设置。

答案 21 :(得分:0)

如果您使用的是javascript,也许您可​​以执行以下操作。 但是,这并不能说明容器的高度...

// whatever string
const myString = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pellentesque sem ut consequat pulvinar. Curabitur vehicula quam sit amet risus aliquet, sed rhoncus tortor fermentum. Etiam ac fermentum nisi. Ut in lobortis eros. Etiam urna felis, interdum sit amet fringilla eu, bibendum et nunc.';

// you can set max string length
const maxStrLength = 100;
const truncatedString = myString.length > maxStrLength ? `${myString.substring(0, maxStrLength)}...` : myString;

console.log(truncatedString);

答案 22 :(得分:-1)

尝试这种简单方法。我在这里也有jsfiddle链接。

这里-webkit-line-clamp具有重要作用。此属性的值决定了可见的行数。

CSS PART

h3{
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      margin: 0px 30px;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
   }

HTML PART

<h3>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</h3>

答案 23 :(得分:-1)

如果您还具有多个元素,并且希望在省略号后使用“阅读更多”按钮进行链接,请查看https://stackoverflow.com/a/51418807/10104342

如果您想要这样的东西:

  

每个月的前10 TB不收费。所有其他流量...阅读更多

答案 24 :(得分:-1)

优点:
+跨浏览器(IE11,Edge,Chrome,Firefox,Safari等)
+最自然的外观

缺点:
-向DOM添加了很多额外的元素

我对看到的任何变通方法都不满意。他们中的大多数使用line-clamp,当前仅在webkit中受支持。因此,我一直在研究它直到找到解决方案。此纯JavaScript解决方案应与IE10及更高版本和所有现代浏览器兼容。在下面的stackoverflow示例空间之外未经测试。

我认为这是一个很好的解决方案。一个大的警告是,它会为容器内的每个单词创建一个跨度,这会影响布局性能,因此您的里程可能会有所不同。

//This is designed to be run on page load, but if you wanted you could put all of this in a function and addEventListener and call it whenever the container is resized.
var $container = document.querySelector('.ellipses-container');

//optional - show the full text on hover with a simple title attribute
$container.title = $container.textContent.trim();

$container.textContent.trim().split(' ').some(function (word) {
  //create a span for each word and append it to the container
  var newWordSpan = document.createElement('span');
  newWordSpan.textContent = word;
  $container.appendChild(newWordSpan);
  
  if (newWordSpan.getBoundingClientRect().bottom > $container.getBoundingClientRect().bottom) {
    //it gets into this block for the first element that has part of itself below the bottom of the container
    //get the last visible element
    var containerChildNodes = $container.childNodes;
    var lastVisibleElement = containerChildNodes[containerChildNodes.length - 2];
    
    //replace this final span with the ellipsis character
    newWordSpan.textContent = '\u2026';
    
    //if the last visible word ended very near the end of the line the ellipsis will have wrapped to the next line, so we need to remove letters from the last visible word
    while (lastVisibleElement.textContent != "" && newWordSpan.getBoundingClientRect().bottom > $container.getBoundingClientRect().bottom) {
      lastVisibleElement.style.marginRight = 0;
      lastVisibleElement.textContent = lastVisibleElement.textContent.slice(0, -1);
    }
    
    //using .some() so that we can short circuit at this point and no more spans will be added
    return true;
  }
});
.multi-line-container {
  border: 1px solid lightgrey;
  padding: 4px;
  height: 150px;
  width: 300px;
}

.ellipses-container {
  display: inline-flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: flex-start; /* optionally use align-content:stretch, the default, if you don't like the extra space at the bottom of the box if there's a half-line gap */
  overflow: hidden;
  position: relative;
}

.ellipses-container > span {
  flex: 0 0 auto;
  margin-right: .25em;
}

.text-body {
  display: none;
}
<div class="multi-line-container ellipses-container">
  <div class="text-body ellipses-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque luctus ut massa eget porttitor. Nulla a eros sit amet ex scelerisque iaculis nec vitae turpis. Sed pharetra tincidunt ante, in mollis turpis consectetur at. Praesent venenatis pulvinar lectus, at tincidunt nunc finibus non. Duis tortor lectus, elementum faucibus bibendum vitae, egestas bibendum ex. Maecenas vitae augue vitae dui condimentum imperdiet sit amet mattis quam. Duis eleifend scelerisque magna sed imperdiet. Mauris tempus rutrum metus, a ullamcorper erat fringilla a. Suspendisse potenti. Praesent et mi enim. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
  </div>
</div>