Javascript 跨浏览器多行文本溢出,在固定宽度和高度内附加省略号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3404508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross-browser multi-line text overflow with ellipsis appended within a fixed width and height
提问by Edward
I made an image for this question to make it easier to understand.
我为这个问题制作了一个图像,以便更容易理解。
Is it possible to create an ellipsis on a <div>with a fixed width and multiple lines?
是否可以在<div>具有固定宽度和多行的 a上创建省略号?
I've tried some jQuery plugins out here and there, but cannot find the one I'm looking for. Any recommendation? Ideas?
我在这里和那里尝试了一些 jQuery 插件,但找不到我正在寻找的插件。有什么推荐吗?想法?
回答by kapa
Just a quick basic idea.
只是一个快速的基本想法。
I was testing with the following markup:
我正在使用以下标记进行测试:
<div id="fos">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed ipsum a lacus sodales eleifend. Vestibulum lorem felis, rhoncus elementum vestibulum eget, dictum ut velit. Nullam venenatis, elit in suscipit imperdiet, orci purus posuere mauris, quis adipiscing ipsum urna ac quam.</p>
</div>
And CSS:
和 CSS:
#fos { width: 300px; height: 190px; overflow: hidden; }
#fos p { padding: 10px; margin: 0; }
Applying this jQuery will accomplish the desired result:
应用此 jQuery 将实现所需的结果:
var $p = $('#fos p');
var divh = $('#fos').height();
while ($p.outerHeight() > divh) {
$p.text(function (index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
It repeatedly tries to remove the last word of the text until it reaches the desired size. Because of the overflow: hidden; the process remains invisible and even with JS turned off the result remains 'visually correct' (without the "..." of course).
它反复尝试删除文本的最后一个单词,直到达到所需的大小。因为溢出:隐藏;该过程仍然不可见,即使关闭 JS,结果仍然“视觉上正确”(当然没有“...”)。
If you combine this with a sensible truncation on the server-side (that leaves only a small overhead) then it will run quicker :).
如果您将此与服务器端的合理截断相结合(只留下很小的开销),那么它会运行得更快:)。
Again, this is not a complete solution, just an idea.
同样,这不是一个完整的解决方案,只是一个想法。
UPDATE:Added a jsFiddle Demo.
更新:添加了一个jsFiddle Demo。
回答by Matt
回答by Adrien Be
Javascript libraries for "line clamping"
用于“线夹”的 Javascript 库
Note that "line clamping" is also referred as "Ellipsis on block of multi-lines" or "vertical ellipsis".
请注意,“线夹”也称为“多线块上的省略号”或“垂直省略号”。
github.com/BeSite/jQuery.dotdotdot
github.com/BeSite/jQuery.dotdotdot
- Pros: 2.5Kb (minified & gzipped), no big activity on repo but not bad either
- Cons: jQuery dependency, paid for commercial use (CC-BY-NC-4.0 license)
- my 2 cents: stackoverflow.com/questions/25187774/read-more-and-read-less-with-dotdotdot-jquery/29118739#29118739
- helpful stackoverflow.com/questions/19015945/jquery-dotdotdot-expand-truncate-text-onclick
- helpful gist.github.com/chiragparekh/c7e33dc749ed25544bde
- 优点:2.5Kb(缩小和压缩),repo 上没有大的活动,但也不错
- 缺点:jQuery 依赖,付费用于商业用途(CC-BY-NC-4.0 许可)
- 我的 2 美分:stackoverflow.com/questions/25187774/read-more-and-read-less-with-dotdotdot-jquery/29118739#29118739
- 有用的stackoverflow.com/questions/19015945/jquery-dotdotdot-expand-truncate-text-onclick
- 有用的要点.github.com/chiragparekh/c7e33dc749ed25544bde
github.com/josephschmitt/Clamp.js
github.com/josephschmitt/Clamp.js
- Cons: code repo barely active
- informative reusablebits.com/post/2980974411/clamp-js-v0-2-explanations-and-performance
Here are a few more I did not investigate yet:
这里还有一些我还没有研究过:
- github.com/ftlabs/ftellipsis
- github.com/micjamking/Succinct
- github.com/pvdspek/jquery.autoellipsisand pvdspek.github.io/jquery.autoellipsis
- github.com/rviscomi/trunk8
- github.com/dobiatowski/jQuery.FastEllipsis
- github.com/theproductguy/ThreeDots
- github.com/tbasse/jquery-truncate
- github.com/kbwood/more
- github.com/ftlabs/ftellipsis
- github.com/micjamking/Succinct
- github.com/pvdspek/jquery.autoellipsis和pvdspek.github.io/jquery.autoellipsis
- github.com/rviscomi/trunk8
- github.com/dobiatowski/jQuery.FastEllipsis
- github.com/theproductguy/ThreeDots
- github.com/tbasse/jquery-truncate
- github.com/kbwood/更多
CSS solutions for line clamping
用于线夹的 CSS 解决方案
There are some CSS solutions, but the simplest uses -webkit-line-clampwhich has poor browser support. See live demo on jsfiddle.net/AdrienBe/jthu55v7/
有一些 CSS 解决方案,但最简单的用途-webkit-line-clamp是浏览器支持不佳。在jsfiddle.net/AdrienBe/jthu55v7/上查看现场演示
Many people went to great efforts in order to make this happen using CSS only. See articles and questions about it:
为了仅使用 CSS 实现这一点,许多人付出了巨大的努力。请参阅有关它的文章和问题:
- css-tricks.com/line-clampin: 5 stars article on line camplin
- mobify.com/blog/multiline-ellipsis-in-pure-css: CSS only
- cssmojo.com/line-clamp_for_non_webkit-based_browsers/: "mimic" -webkit-line-clamp in non webkit browsers
- With CSS, use "..." for overflowed block of multi-lines
- Cross-browser multi-line text overflow with ellipsis appended within a width and height fixed `<div>`
- How to display only the first few lines of a div (clamping)?
- jquery limit lines in a paragraph and apply three periods to the end
- Limit text length to n lines using CSS
- css-tricks.com/line-clampin:在线 Camplin 上的 5 星文章
- mobify.com/blog/multiline-ellipsis-in-pure-css:仅 CSS
- cssmojo.com/line-clamp_for_non_webkit-based_browsers/: "mimic" -webkit-line-clamp 在非 webkit 浏览器中
- 使用 CSS,对溢出的多行块使用“...”
- 跨浏览器多行文本溢出,在宽度和高度固定的 `<div>` 内附加省略号
- 如何仅显示 div 的前几行(钳位)?
- jquery 限制段落中的行并在末尾应用三个句点
- 使用 CSS 将文本长度限制为 n 行
What I'd recommend
我会推荐什么
Keep it simple. Unless you have great amount of time to dedicate to this feature, go for the simplest & tested solution: simple CSS or a well tested javascript library.
把事情简单化。除非您有大量时间专门用于此功能,否则请选择最简单且经过测试的解决方案:简单的 CSS 或经过良好测试的 javascript 库。
Go for something fancy/complex/highly-customized & you will pay the price for this down the road.
选择一些花哨/复杂/高度定制的东西,你将为此付出代价。
What others do
别人做什么
Having a fade out like Airbnb does might be a good solution. It probably is basic CSS coupled with basic jQuery. Actually, it seems very similar to this solution on CSSTricks
像 Airbnb 那样淡出可能是一个很好的解决方案。它可能是基本的 CSS 加上基本的 jQuery。实际上,它似乎与CSSTricks上的这个解决方案非常相似
Oh, and if you look for design inspirations:
哦,如果你寻找设计灵感:
- smashingmagazine.com/2009/07/designing-read-more-and-continue-reading-links/, from 2009 though...
- Dribbble probably has interesting designs...I could not find a way to gather them though (via search or tags), feel free to share a relevant link
- smashingmagazine.com/2009/07/designing-read-more-and-continue-reading-links/,从 2009 年开始……
- Dribbble 可能有有趣的设计......虽然我找不到收集它们的方法(通过搜索或标签),请随意分享相关链接
回答by Samuel Rossille
There is no such feature in HTML, and this is very frustrating.
HTML 中没有这样的功能,这很令人沮丧。
I have developed a libraryto deal with this.
我开发了一个库来处理这个问题。
- Multiline text-overflow: ellipsis
- Multiline text with technologies that does not support it: SVG, Canvas for example
- Have exactly the same line breaks in your SVG text, in your HTML rendering, and in your PDF export for example
- 多行文本溢出:省略号
- 使用不支持它的技术的多行文本:例如 SVG、Canvas
- 例如,在 SVG 文本、HTML 渲染和 PDF 导出中具有完全相同的换行符
Check out my sitefor screenshot, tutorial, and dowload link.
查看我的网站以获取屏幕截图、教程和下载链接。
回答by prashn64
Pure JS solution based on ba?megakapa's solution, and some cleanup to account for people who try to give a height/max-height that is less than the element's lineHeight:
基于 ba?megakapa 解决方案的纯 JS 解决方案,以及一些清理,以解决那些试图给出小于元素 lineHeight 的高度/最大高度的人:
var truncationEl = document.getElementById('truncation-test');
function calculateTruncation(el) {
var text;
while(el.clientHeight < el.scrollHeight) {
text = el.innerHTML.trim();
if(text.split(' ').length <= 1) {
break;
}
el.innerHTML = text.replace(/\W*\s(\S)*$/, '...');
}
}
calculateTruncation(truncationEl);
回答by Miriam Salzer
I have a solution which works well but instead an ellipsis it uses a gradient. The advantages are that you don't have to do any JavaScript calculations and it works for variable width containers including table cells. It uses a couple of extra divs, but it's very easy to implement.
我有一个运行良好的解决方案,但它使用渐变代替省略号。优点是您不必进行任何 JavaScript 计算,并且它适用于包括表格单元格在内的可变宽度容器。它使用了几个额外的 div,但它很容易实现。
http://salzerdesign.com/blog/?p=453
http://salzerdesign.com/blog/?p=453
Edit: Sorry, I did't know that the link wasn't enough. The solution is to put a div around the text, and style the div to control the overflow. Inside the div put another div with a "fade" gradient which can be made by using CSS or an image (for old IE). The gradient goes from transparent to the background color of the table cell and is a bit wider than an ellipsis. If the text is long and overflows, it goes under the "fade" div and looks "faded out". If the text is short, the fade is invisible so there is no problem. The two containers can be adjusted to let one or multiple lines show by setting the height of the container as a multiple of the text line height. The "fade" div can be positioned to only cover the last line.
编辑:对不起,我不知道链接还不够。解决方法是在文本周围放置一个div,并设置div的样式以控制溢出。在 div 内放置另一个带有“淡入淡出”渐变的 div,可以使用 CSS 或图像(对于旧的 IE)来制作。渐变从透明到表格单元格的背景颜色,比省略号稍宽。如果文本很长并且溢出,它会进入“淡出”div 并看起来“淡出”。如果文本很短,淡入淡出是不可见的,所以没有问题。通过将容器的高度设置为文本行高的倍数,可以调整两个容器以显示一行或多行。“淡入淡出”div 可以定位为仅覆盖最后一行。
回答by Aaron Hoffman
Here is a pure CSS way to accomplish this: http://www.mobify.com/blog/multiline-ellipsis-in-pure-css/
这是实现此目的的纯 CSS 方式:http: //www.mobify.com/blog/multiline-ellipsis-in-pure-css/
Here is a summary:
这是一个总结:


<html>
<head>
<style>
html, body, p { margin: 0; padding: 0; font-family: sans-serif;}
.ellipsis {
overflow: hidden;
height: 200px;
line-height: 25px;
margin: 20px;
border: 5px solid #AAA; }
.ellipsis:before {
content:"";
float: left;
width: 5px; height: 200px; }
.ellipsis > *:first-child {
float: right;
width: 100%;
margin-left: -5px; }
.ellipsis:after {
content: "026";
box-sizing: content-box;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
float: right; position: relative;
top: -25px; left: 100%;
width: 3em; margin-left: -3em;
padding-right: 5px;
text-align: right;
background: -webkit-gradient(linear, left top, right top,
from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); }
</style>
</head>
<body>
<div class="ellipsis">
<div>
<p>Call me Ishmael.....</p>
</div>
</div>
</body>
</html>
回答by Penny Liu
You can use -webkit-line-clampproperty with div.
您可以将-webkit-line-clamp属性与div.
-webkit-line-clamp: <integer>which means set the maximum number of lines before truncating the content and then displays an ellipsis (…)at the end of the last line.
-webkit-line-clamp: <integer>这意味着在截断内容之前设置最大行数,然后(…)在最后一行的末尾显示省略号。
div {
width: 205px;
height: 40px;
background-color: gainsboro;
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
/* <integer> values */
-webkit-line-clamp: 2;
}
<div>This is a multi-lines text block, some lines inside the div, while some outside</div>
回答by thdoan
Here's a vanilla JavaScript solution you can use in a pinch:
这是您可以在紧要关头使用的普通 JavaScript 解决方案:
// @param 1 = element containing text to truncate
// @param 2 = the maximum number of lines to show
function limitLines(el, nLines) {
var nHeight,
el2 = el.cloneNode(true);
// Create clone to determine line height
el2.style.position = 'absolute';
el2.style.top = '0';
el2.style.width = '10%';
el2.style.overflow = 'hidden';
el2.style.visibility = 'hidden';
el2.style.whiteSpace = 'nowrap';
el.parentNode.appendChild(el2);
nHeight = (el2.clientHeight+2)*nLines; // Add 2 pixels of slack
// Clean up
el.parentNode.removeChild(el2);
el2 = null;
// Truncate until desired nLines reached
if (el.clientHeight > nHeight) {
var i = 0,
imax = nLines * 35;
while (el.clientHeight > nHeight) {
el.innerHTML = el.textContent.slice(0, -2) + '…';
++i;
// Prevent infinite loop in "print" media query caused by
// Bootstrap 3 CSS: a[href]:after { content:" (" attr(href) ")"; }
if (i===imax) break;
}
}
}
limitLines(document.getElementById('target'), 7);
#test {
width: 320px;
font-size: 18px;
}
<div id="test">
<p>Paragraph 1</p>
<p id="target">Lorem ipsum dolor sit amet, consectetur adipisicing 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 pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Paragraph 3</p>
</div>
You can play around with it in the codepen below. Try changing the font size in the CSS panel and make a minor edit in the HTML panel (e.g., add an extra space somewhere) to update the results. Regardless of the font size, the middle paragraph should always be truncated to the number of lines in the second parameter passed to limitLines().
您可以在下面的代码笔中使用它。尝试在 CSS 面板中更改字体大小并在 HTML 面板中进行少量编辑(例如,在某处添加额外的空格)以更新结果。无论字体大小如何,中间段落都应始终截断为传递给 limitLines() 的第二个参数中的行数。
Codepen:http://codepen.io/thdoan/pen/BoXbEK
代码笔:http ://codepen.io/thdoan/pen/BoXbEK
回答by Yulian
Found this short CSS-onlysolution in Adrien Be's answer:
在Adrien Be 的回答中找到了这个仅使用CSS 的简短解决方案:
.line-clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
As of March 2020browser supportis 95.3%, not being supported in IE and Opera Mini. Works on Chrome, Safari, Firefox and Edge.
截至2020 年 3 月,浏览器支持率为95.3%,IE 和 Opera Mini 不支持。适用于 Chrome、Safari、Firefox 和 Edge。

