有效的跨浏览器解决方案
这个问题多年来一直困扰着我们大家。
为了在所有情况下提供帮助,我列出了仅 CSS 方法,以及 jQuery 方法,以防 css 警告出现问题。
这是我提出的一个仅 CSS 的解决方案,它适用于所有情况,但有一些小注意事项。
基础很简单,它隐藏跨度的溢出,并根据 Eugene Xa 的建议根据行高设置最大高度。
然后在包含 div 后面有一个伪类,可以很好地放置省略号。
注意事项
此解决方案将始终放置省略号,无论是否需要它。
如果最后一行以结束句结尾,您将得到四个点......
您需要对合理的文本对齐感到满意。
省略号将位于文本的右侧,这可能看起来很草率。
代码+片段
jsfiddle
.text {
position: relative;
font-size: 14px;
color: black;
width: 250px; /* Could be anything you like. */
}
.text-concat {
position: relative;
display: inline-block;
word-wrap: break-word;
overflow: hidden;
max-height: 3.6em; /* (Number of lines you want visible) * (line-height) */
line-height: 1.2em;
text-align:justify;
}
.text.ellipsis::after {
content: "...";
position: absolute;
right: -12px;
bottom: 4px;
}
/* Right and bottom for the psudo class are px based on various factors, font-size etc... Tweak for your own needs. */
<div class="text ellipsis">
<span class="text-concat">
Lorem ipsum dolor sit amet, nibh eleifend cu his, porro fugit mandamus no mea. Sit tale facete voluptatum ea, ad sumo altera scripta per, eius ullum feugait id duo. At nominavi pericula persecuti ius, sea at sonet tincidunt, cu posse facilisis eos. Aliquid philosophia contentiones id eos, per cu atqui option disputationi, no vis nobis vidisse. Eu has mentitum conclusionemque, primis deterruisset est in.
Virtute feugait ei vim. Commune honestatis accommodare pri ex. Ut est civibus accusam, pro principes conceptam ei, et duo case veniam. Partiendo concludaturque at duo. Ei eirmod verear consequuntur pri. Esse malis facilisis ex vix, cu hinc suavitate scriptorem pri.
</span>
</div>
运行代码片段隐藏结果
展开片段
jQuery 方法
我认为这是最好的解决方案,但并不是每个人都可以使用 JS。基本上,jQuery 将检查任何 .text 元素,如果字符数多于预设的最大变量,它将截断其余部分并添加省略号。
这种方法没有任何警告,但是这个代码示例只是为了演示基本思想 - 我不会在生产中使用它而不对其进行改进,原因有两个:
1)它将重写.text elems的内部html。无论需要与否。 2)它没有测试来检查内部 html 是否没有嵌套元素 - 所以你非常依赖作者正确使用 .text 。
已编辑
感谢您的关注@markzzz
代码和片段
jsfiddle
setTimeout(function()
{
var max = 200;
var tot, str;
$('.text').each(function() {
str = String($(this).html());
tot = str.length;
str = (tot <= max)
? str
: str.substring(0,(max + 1))+"...";
$(this).html(str);
});
},500); // Delayed for example only.
.text {
position: relative;
font-size: 14px;
color: black;
font-family: sans-serif;
width: 250px; /* Could be anything you like. */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="text">
Old men tend to forget what thought was like in their youth; they forget the quickness of the mental jump, the daring of the youthful intuition, the agility of the fresh insight. They become accustomed to the more plodding varieties of reason, and because this is more than made up by the accumulation of experience, old men think themselves wiser than the young.
</p>
<p class="text">
Old men tend to forget what thought was like in their youth;
</p>
<!-- Working Cross-browser Solution
This is a jQuery approach to limiting a body of text to n words, and end with an ellipsis -->
展开片段