截断文本以适合 3 行并在 Html 中显示三个点

问题描述 投票:0回答:5

我需要将文本显示为段落,但仅显示三行并截断测试,同时在段落末尾添加...(三个点)。

javascript html jquery-mobile
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);


16
投票

计算可以容纳 3 行的字符串的最大长度并使用以下脚本

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

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>


1
投票

尝试以下 CSS 属性:

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

0
投票

仅使用 CSS 即可完成

line-clamp
属性

(参见浏览器支持表)

它只能与设置为

-webkit-box
-webkit-inline-box
的显示属性以及设置为
-webkit-box-orient
vertical
属性结合使用。

在大多数情况下,您还需要将
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>

© www.soinside.com 2019 - 2024. All rights reserved.