在特定行数后插入省略号

时间:2015-03-20 06:28:52

标签: javascript html css

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

<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>

我在此网站上查看了很多答案,例如this onethis one以及其他地方,例如http://codepen.io/martinwolf/pen/qlFdphttps://css-tricks.com/line-clampin/,但都没有适用于这种情况,我希望在最后一行的最后一个单词后面的省略号,即使它没有到达行的末尾,并且有多个<p>标记。

我在Angular中使用JavaScript。

2 个答案:

答案 0 :(得分:2)

是的,你可以使用一些插件,但这种逻辑并不难写你自己。基本概念是在文本适合之前继续减少文本量。这听起来很昂贵,但在实践中它工作正常,并且可以在必要时进行优化。

// 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)) + '...';
  }

}

要使用它:

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

要与HTML内容一起使用,请根据需要调整/扩展。

答案 1 :(得分:0)

尝试使用jQuery dotdotdot插件。网址:http://dotdotdot.frebsite.nl/

我在jsFiddle Link

中提供了代码示例

以下是代码:

$(document).ready(function() {
	$(".myText").dotdotdot();
});
p {
    margin:0;
    padding:0;
    font:12px/15px Verdana, Geneva, Tahoma, Arial, Helvetica, sans-serif;
}
.myText {
    height:75px; /*  this needs to be the height of 5 lines of text. Here it is 15px (line-height of one line) * 5 = 75px */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.dotdotdot/1.7.2/jquery.dotdotdot.min.js"></script>

<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>

希望这有帮助。