是否有一个解决方案,添加省略号内的最后一行与流体高度(20%)div ?
我在CSS中找到了-webkit-线夹函数,但在我的情况下,行号将取决于窗口大小。
p {
width:100%;
height:20%;
background:red;
position:absolute;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>
我有这个JSFiddle来说明这个问题。
https://jsfiddle.net/96knodm6/
如果您想对单行文本应用省略号(…),CSS通过text-overflow属性使之变得有些容易。这仍然有点棘手(由于所有的要求-请参阅下面),但文本溢出使它成为可能和可靠的。
然而,如果您想在多行文本上使用省略号——就像这里的情况一样——那么就别指望有什么乐趣了。CSS没有标准的方法来做到这一点,而且变通方法是随机的。
单行文本的省略
使用文本溢出,省略号可以应用于单行文本。CSS的要求如下:
必须有一个宽度,最大宽度或弹性基础
必须有空白:nowrap
必须有溢出的值而不是可见的
必须显示:块或内联块
(或功能对等物,如伸缩项目)。
这是可行的:
p {
width: 200px;
white-space: nowrap;
overflow: hidden;
display: inline-block;
text-overflow: ellipsis;
border: 1px solid #ddd;
margin: 0;
}
<p>
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
</p>
新美国jsFiddle
但是,尝试删除宽度,或让溢出默认为可见,或删除空白:nowrap,或使用块容器元素以外的东西,AND,省略号失败得很惨。
这里有一个重要的结论:text-overflow:省略号对多行文本没有影响。(仅white-space: nowrap要求就消除了这种可能性。)
p {
width: 200px;
/* white-space: nowrap; */
height: 90px; /* new */
overflow: hidden;
display: inline-block;
text-overflow: ellipsis;
border: 1px solid #ddd;
margin: 0;
}
<p>
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
This is a test of CSS <i>text-overflow: ellipsis</i>.
</p>
新美国jsFiddle
多行文本的省略
因为CSS在多行文本上没有省略号属性,所以创建了各种变通方法。这些方法可以在这里找到:
jQuery dotdotdot……
行截断(截断多行文本)
CSS省略:如何在纯CSS中管理多行省略
多行文本截断的纯CSS解决方案
上面的Mobify链接被删除了,现在引用了archive.org的副本,但似乎在这个代码依赖中实现了。
经过多次尝试,我终于用混合的js / css来处理多行和单行溢出。
CSS3代码:
.forcewrap { // single line ellipsis
-ms-text-overflow: ellipsis;
-o-text-overflow: ellipsis;
text-overflow: ellipsis;
overflow: hidden;
-moz-binding: url( 'bindings.xml#ellipsis' );
white-space: nowrap;
display: block;
max-width: 95%; // spare space for ellipsis
}
.forcewrap.multiline {
line-height: 1.2em; // my line spacing
max-height: 3.6em; // 3 lines
white-space: normal;
}
.manual-ellipsis:after {
content: "\02026"; // '...'
position: absolute; // parent container must be position: relative
right: 10px; // typical padding around my text
bottom: 10px; // same reason as above
padding-left: 5px; // spare some space before ellipsis
background-color: #fff; // hide text behind
}
我简单地检查js代码的溢出在divs,像这样:
function handleMultilineOverflow(div) {
// get actual element that is overflowing, an anchor 'a' in my case
var element = $(div).find('a');
// don't know why but must get scrollHeight by jquery for anchors
if ($(element).innerHeight() < $(element).prop('scrollHeight')) {
$(element).addClass('manual-ellipsis');
}
}
html中的用法示例:
<div class="towrap">
<h4>
<a class="forcewrap multiline" href="/some/ref">Very long text</a>
</h4>
</div>
我只是在这个概念上玩了一下。基本上,如果你可以从你的最后一个字符中删除一个像素,这里是一个纯css和html的解决方案:
其工作方式是将一个div绝对定位在视口的可视区域之下。我们希望随着内容的增长,div向上偏移到可见区域。如果内容增长太多,我们的div将偏移过高,所以我们的内容可以增长的高度的上限。
HTML:
<div class="text-container">
<span class="text-content">
PUT YOUR TEXT HERE
<div class="ellipsis">...</div> // You could even make this a pseudo-element
</span>
</div>
CSS:
.text-container {
position: relative;
display: block;
color: #838485;
width: 24em;
height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
overflow: hidden;
white-space: normal;
}
.text-content {
word-break: break-all;
position: relative;
display: block;
max-height: 3em; // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport
}
.ellipsis {
position: absolute;
right: 0;
top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
text-align: left;
background: white;
}
我已经在Chrome、FF、Safari和IE 11上进行了测试。
你可以在这里查看:http://codepen.io/puopg/pen/vKWJwK
你甚至可以用一些CSS魔术来缓解字符的突然切断。
编辑:我猜这强加的一件事是word-break: break-all,否则内容不会扩展到视口的最末端。:(
我终于找到了做我想做的事的方法。
作为段落和文章的包装。
如果你想根据文章高度(也取决于窗口高度)对p应用省略号,你需要得到文章的高度,p的行高度,然后articleHeight/lineHeight来找到可以动态添加的线夹的数量。
唯一的问题是行高应该在css文件中声明。
检查下面的代码。如果你改变窗户的高度,线夹也会改变。创建一个旨在实现这一目标的插件是很好的。
斯菲德尔
function lineclamp() {
var lineheight = parseFloat($('p').css('line-height'));
var articleheight = $('article').height();
var calc = parseInt(articleheight/lineheight);
$("p").css({"-webkit-line-clamp": "" + calc + ""});
}
$(document).ready(function() {
lineclamp();
});
$( window ).resize(function() {
lineclamp();
});
article {
height:60%;
background:red;
position:absolute;
}
p {
margin:0;
line-height:120%;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque lorem ligula, lacinia a justo sed, porttitor vulputate risus. In non feugiat risus. Sed vitae urna nisl. Duis suscipit volutpat sollicitudin. Donec ac massa elementum massa condimentum mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla sollicitudin sapien at enim sodales dapibus. Pellentesque sed nisl eu sem aliquam tempus nec ut leo. Quisque rutrum nulla nec aliquam placerat. Fusce a massa ut sem egestas imperdiet. Sed sollicitudin id dolor egestas malesuada. Quisque placerat lobortis ante, id ultrices ipsum hendrerit nec. Quisque quis ultrices erat.Nulla gravida ipsum nec sapien pellentesque pharetra. Suspendisse egestas aliquam nunc vel egestas. Nullam scelerisque purus interdum lectus consectetur mattis. Aliquam nunc erat, accumsan ut posuere eu, vehicula consequat ipsum. Fusce vel ex quis sem tristique imperdiet vel in mi. Cras leo orci, fermentum vitae volutpat vitae, convallis semper libero. Phasellus a volutpat diam. Ut pulvinar purus felis, eu vehicula enim aliquet vitae. Suspendisse quis lorem facilisis ante interdum euismod et vitae risus. Vestibulum varius nulla et enim malesuada fringilla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque lorem ligula, lacinia a justo sed, porttitor vulputate risus. In non feugiat risus. Sed vitae urna nisl. Duis suscipit volutpat sollicitudin. Donec ac massa elementum massa condimentum mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla sollicitudin sapien at enim sodales dapibus. Pellentesque sed nisl eu sem aliquam tempus nec ut leo. Quisque rutrum nulla nec aliquam placerat. Fusce a massa ut sem egestas imperdiet. Sed sollicitudin id dolor egestas malesuada. Quisque placerat lobortis ante, id ultrices ipsum hendrerit nec.</p></article>
请检查这个css多行文本的省略
body {
margin: 0;
padding: 50px;
}
/* mixin for multiline */
.block-with-text {
overflow: hidden;
position: relative;
line-height: 1.2em;
max-height: 6em;
text-align: justify;
margin-right: -1em;
padding-right: 1em;
}
.block-with-text:before {
content: '...';
position: absolute;
right: 0;
bottom: 0;
}
.block-with-text:after {
content: '';
position: absolute;
right: 0;
width: 1em;
height: 1em;
margin-top: 0.2em;
background: white;
}
<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon; use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>
优点:
+跨浏览器(IE11, Edge, Chrome, Firefox, Safari等)
+最自然的外观
缺点:
-为DOM添加了很多额外的元素
我对我见过的所有变通办法都不满意。他们大多数使用线钳,目前只支持在webkit。所以我一直在研究,直到我想出了一个解决方案。这个纯javascript解决方案应该与IE10和更高版本以及所有现代浏览器兼容。在下面的stackoverflow示例空间之外,这是未经测试的。
我认为这是一个很好的解决方案。一个重要的警告是,它为容器内的每个单词创建了一个跨度,这将影响布局性能,因此您的里程可能会有所不同。
//This is designed to be run on page load, but if you wanted you could put all of this in a function and addEventListener and call it whenever the container is resized.
var $container = document.querySelector('.ellipses-container');
//optional - show the full text on hover with a simple title attribute
$container.title = $container.textContent.trim();
$container.textContent.trim().split(' ').some(function (word) {
//create a span for each word and append it to the container
var newWordSpan = document.createElement('span');
newWordSpan.textContent = word;
$container.appendChild(newWordSpan);
if (newWordSpan.getBoundingClientRect().bottom > $container.getBoundingClientRect().bottom) {
//it gets into this block for the first element that has part of itself below the bottom of the container
//get the last visible element
var containerChildNodes = $container.childNodes;
var lastVisibleElement = containerChildNodes[containerChildNodes.length - 2];
//replace this final span with the ellipsis character
newWordSpan.textContent = '\u2026';
//if the last visible word ended very near the end of the line the ellipsis will have wrapped to the next line, so we need to remove letters from the last visible word
while (lastVisibleElement.textContent != "" && newWordSpan.getBoundingClientRect().bottom > $container.getBoundingClientRect().bottom) {
lastVisibleElement.style.marginRight = 0;
lastVisibleElement.textContent = lastVisibleElement.textContent.slice(0, -1);
}
//using .some() so that we can short circuit at this point and no more spans will be added
return true;
}
});
.multi-line-container {
border: 1px solid lightgrey;
padding: 4px;
height: 150px;
width: 300px;
}
.ellipses-container {
display: inline-flex;
flex-wrap: wrap;
justify-content: flex-start;
align-content: flex-start; /* optionally use align-content:stretch, the default, if you don't like the extra space at the bottom of the box if there's a half-line gap */
overflow: hidden;
position: relative;
}
.ellipses-container > span {
flex: 0 0 auto;
margin-right: .25em;
}
.text-body {
display: none;
}
<div class="multi-line-container ellipses-container">
<div class="text-body ellipses-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque luctus ut massa eget porttitor. Nulla a eros sit amet ex scelerisque iaculis nec vitae turpis. Sed pharetra tincidunt ante, in mollis turpis consectetur at. Praesent venenatis pulvinar lectus, at tincidunt nunc finibus non. Duis tortor lectus, elementum faucibus bibendum vitae, egestas bibendum ex. Maecenas vitae augue vitae dui condimentum imperdiet sit amet mattis quam. Duis eleifend scelerisque magna sed imperdiet. Mauris tempus rutrum metus, a ullamcorper erat fringilla a. Suspendisse potenti. Praesent et mi enim. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</div>
</div>
请检查下面的代码纯css技巧与适当的对齐,支持所有浏览器
.block-with-text {
overflow: hidden;
position: relative;
line-height: 1.2em;
max-height: 103px;
text-align: justify;
padding: 15px;
}
.block-with-text:after {
content: '...';
position: absolute;
right: 15px;
bottom: -4px;
background: linear-gradient(to right, #fffff2, #fff, #fff, #fff);
}
<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon; use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>
p {
width:100%;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
background:#fff;
position:absolute;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>