在特定行数后插入省略号 [英] Insert ellipsis after specific number of lines

查看:70
本文介绍了在特定行数后插入省略号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图只显示文本的前5行。问题是文本设置的方式是div中的多个< p> 标签,例如

 < div class =myText> 
< p>一些文字< / p>
< p>一些文字< / p>
< p>一些文字< / p>
< p>一些文字< / p>
< p>一些文字< / p>
< p>一些文字< / p>
< p>一些文字< / p>
< / div>

我在这个网站上看过很多答案,例如这一个 this one 和其他地方,例如 http://codepen.io/martinwolf/pen/qlFdp https://css-tricks.com/line-clampin/ ,但它们都不适用于这种情况,我想在最后一个字之后的省略号即使没有到达行尾,并且有多个< p> 标签。



我使用JavaScript和Angular。

解决方案

是的,你可以使用一些插件,但这个逻辑不是难以置信写自己。基本概念是保持减少文本的数量,直到它适合。

  //使用文本填充元素适合高度
function truncate(elt,content,height){

function getHeight(elt){return elt.getBoundingClientRect()。height; }
function shorten(str){return str.slice(0,-1); }

elt.style.height =auto;
elt.textContent = content;

//缩短字符串,直到它垂直。
while(getHeight(elt)> height&&&content){
elt.textContent =(content = shorten(content))+'...'
}

}

使用:

  truncate(div,一些非常长的文本将被截断,200)
pre>

要使用HTML内容,请根据需要进行调整/扩展。


I am trying to display only the first 5 lines of text. The problem is that the way the text is set up is multiple <p> tags within a div, such as

<div class="myText">
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
  <p>some text</p>
</div>

I have looked at many answers on this site such as this one, and this one and in other places, such as http://codepen.io/martinwolf/pen/qlFdp, and https://css-tricks.com/line-clampin/, but none of them work for this case, where I would want the ellipsis after the last word on the last line even if it does not reach the end of the line, and there are multiple <p> tags.

I am using JavaScript with Angular.

解决方案

Yes, you could use some plug-in, but this logic is not incredibly hard to write yourself. The basic notion is to keep reducing the amount of text until it fits. This sounds expensive, but in practice it works fine, and could be optimized if necessary.

// Populate an element with text so as to fit into height
function truncate(elt, content, height) {

  function getHeight(elt) { return elt.getBoundingClientRect().height; }
  function shorten(str)   { return str.slice(0, -1); }

  elt.style.height = "auto";
  elt.textContent = content;

  // Shorten the string until it fits vertically.
  while (getHeight(elt) > height && content) {
    elt.textContent = (content = shorten(content)) + '...';
  }

}

To use this:

truncate(div, "Some very long text to be truncated", 200)

To use with HTML content, adapt/extend as necessary.

这篇关于在特定行数后插入省略号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆