我想当文本<=2 lines, then display 2 lines without "...". However, if the text is > 2行时显示,然后在中间添加“...”。 在我的代码中,我可以在中间添加“...”,但是当文本小于或等于2行时,它仍然显示“...”。我想要的是,当文本 <= 2 lines it still displays full text, and if text > 2 然后在中间显示“...”时。 这是我的代码:
const Main=()=>{
return(
<div>
<p>{truncateMiddle(textDummy)}</p>
</div>
)
const truncateMiddle=(text)=>{
const offset = 50;
const ellipsis = '...'
const len = text.length;
const tail = text.slice(len - offset, len);
let head = ""
let end = len - offset;
let start = 50;
while (start < end - 1) {
const curr = Math.floor((end - start) / 2 + start);
head = text.slice(0, curr);
end = curr;
}
head = text.slice(0, start || 1);
return head + ellipsis + tail;
}
如果改用纯 CSS 会怎样?
p {
display: -webkit-box;
-webkit-line-clamp: 2; // number of lines
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}