我想在内容末尾添加一个带有换行符的省略号,如果它溢出了具有最大高度和溢出:隐藏的div。
我已经尝试过这样做,但是我的方法的问题在于,如果有两个换行符,则输出中只会显示一个换行符。这就是小提琴链接 https://jsfiddle.net/AkshayaKT/qg8yurt5/
var ellipsesText = "...";
$( '.card-content' ).each (function () {
var content = $( this ).html(),
divheight = $( this ).height(),
lineheight = $( this ).css( 'line-height' ).replace( "px", "" ),
lines = Math.round( divheight / parseInt( lineheight ) ),
eachLines = content.split( /<br>/ );
if ( lines >= 3 ) {
var replaceTxt = "";
$.each( eachLines, function( index, item ) {
if ( index <= 2 ) {
if ( item == "" ) {
replaceTxt = replaceTxt + '<br>';
} else {
replaceTxt = replaceTxt + item;
}
}
} );
replaceTxt = replaceTxt + ellipsesText;
$( this ).html( replaceTxt );
}
} );
body {
box-sizing: border-box;
}
.card-content {
font-size: 15px;
font-weight: 400;
color: #333;
max-height: 63px;
margin: 10px;
line-height: 21px;
overflow: hidden;
border: 1px solid;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card-content">What is Lorem Ipsum?<br><br><br><br>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</div>
<div class="card-content">What is Lorem Ipsum?<br><br>hi</div>
split()
删除它拆分的内容并将两者之间的所有内容添加到数组中,因此它将删除原始<br>
。我看到您正在尝试在item
(即行内容(为空时重新添加它们,但是当它不为空时,您没有将它们重新添加。
请参阅更新的小提琴:http://jsfiddle.net/qg8yurt5/6/
var ellipsesText = "...";
$('.card-content').each(function() {
var content = $(this).html(),
divheight = $(this).height(),
lineheight = $(this).css('line-height').replace("px", ""),
lines = Math.round(divheight / parseInt(lineheight)),
eachLines = content.split(/<br>/);
if (lines >= 3) {
var replaceTxt = "";
$.each(eachLines, function(index, item) {
if (index <= 2) {
replaceTxt = replaceTxt + item;
if (index < 2) {
replaceTxt = replaceTxt + '<br>';
}
}
})
replaceTxt = replaceTxt + ellipsesText;
$(this).html(replaceTxt);
}
});
body {
box-sizing: border-box;
}
.card-content {
font-size: 15px;
font-weight: 400;
color: #333;
max-height: 63px;
margin: 10px;
line-height: 21px;
overflow: hidden;
border: 1px solid;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card-content">What is Lorem Ipsum?
<br>
<br>
<br>
<br>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's</div>
<div class="card-content">What is Lorem Ipsum?
<br>
<br>hi</div>
<div class="card-content">No matter what you do.<br>I work just fine<br>And will cut off after 3 lines, and put ellipses on the 3rd line >>> <br>You can't see me</div>