是否有一个解决方案,添加省略号内的最后一行与流体高度(20%)div ?

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

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>

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


当前回答

如果你正在使用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);

其他回答

我只是在这个概念上玩了一下。基本上,如果你可以从你的最后一个字符中删除一个像素,这里是一个纯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魔术来缓解字符的突然切断。

编辑:我猜这强加的一件事是word-break: break-all,否则内容不会扩展到视口的最末端。:(

糟糕的CSS不支持跨浏览器多行夹紧,只有webkit似乎在推动它。

你可以尝试使用一个简单的Javascript省略号库,比如github上的Ellipsity,源代码非常干净和小,所以如果你确实需要做任何额外的改变,它应该很容易。

https://github.com/Xela101/Ellipsity

You can achieve this by a few lines of CSS and JS.

CSS:

        div.clip-context {
          max-height: 95px;
          word-break: break-all;
          white-space: normal;
          word-wrap: break-word; //Breaking unicode line for MS-Edge works with this property;
        }

JS:

        $(document).ready(function(){
             for(let c of $("div.clip-context")){
                    //If each of element content exceeds 95px its css height, extract some first 
                    //lines by specifying first length of its text content. 
                   if($(c).innerHeight() >= 95){
                        //Define text length for extracting, here 170.
                        $(c).text($(c).text().substr(0, 170)); 
                        $(c).append(" ...");
                   }
             }

        });

HTML:

        <div class="clip-context">
            (Here some text)
        </div>

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

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

我对我见过的所有变通办法都不满意。他们大多数使用线钳,目前只支持在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>

对此,我提出了自己的解决方案:

/*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)*$/, '...');
            });
        }
    });
}