Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - Insert ellipsis after specific number of lines

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...