在HTML中将文本截断为三行并在末尾显示三个点

10

我需要将一段文本显示为段落,但只显示三行,并在段落结尾处截断文本并添加...(三个点)。

5个回答

17

我使用与 @zavg 相同的逻辑,但做了一些改进:

  • 使用单个 字符。
  • 遵守最大尺寸限制。

function truncate(source, size) {
  return source.length > size ? source.slice(0, size - 1) + "…" : source;
}

var res = truncate('Truncate text to fit in 3 lines', 14);
console.log(res);


非常棒的解决方案。谢谢。 - HellaDev

16

计算可以适配到3行的字符串的最大长度,并使用以下脚本:

var maxLength = 140;
var result = yourString.substring(0, maxLength) + '...';

1
如何决定最大长度?为什么是140? - Sundeep Saluja
@SundeepSaluja 140 值仅用于代码示例(它是 Twitter 的常量)。您应该通过实验确定三行中适合多少个符号。 - zavg

15

.class-name {
        display: block;
        white-space: nowrap;
        width: 15em;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    <div style="height: 15vh; padding: 10px;
                background:#dee0e5">
    <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum is simply dummy text of the printing and typesetting industry</span>
    </div>

<div style="height: 15vh;padding: 10px; margin-top:5px;
                background:#aff8af">
    <span class="class-name">Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum is simply dummy text of the printing and typesetting industry</span>
    </div>


你如何对三行执行相同的操作? - Robert Ravikumar

1
尝试以下 CSS 属性:

.your-class-name {
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  line-clamp: 3;
}

5
你需要发布一个演示,因为我认为这个没有任何作用。 - M H

0

可以只使用CSS来完成,使用line-clamp属性

(请参考浏览器支持表)

它只能与-webkit-box-webkit-inline-box设置的display属性以及vertical设置的-webkit-box-orient属性结合使用。

在大多数情况下,您还需要将overflow设置为hidden,否则内容将不会被裁剪,但在指定的行数后仍会显示省略号。

代码:

p {
  font: 20px Arial;
  width: 400px;
  border: 1px dashed silver;  
  
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla</p>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接