我试图只显示前 5 行文本。问题是文本的设置方式是多个<p>
div 中的标签,例如
<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 one , 和 this one和其他地方,例如http://codepen.io/martinwolf/pen/qlFdp , 和 https://css-tricks.com/line-clampin/ , 但它们都不适用于这种情况,我希望在最后一行的最后一个单词之后有省略号,即使它没有到达行尾,并且有多个 <p>
标签。
我在 Angular 中使用 JavaScript。
最佳答案
是的,你可以使用一些插件,但是你自己写这个逻辑并不难。基本概念是不断减少文本量,直到适合为止。这听起来很昂贵,但实际上效果很好,并且可以根据需要进行优化。
// 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 内容一起使用,请根据需要进行调整/扩展。
关于javascript - 在特定行数后插入省略号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29160687/