The mobile version has an effect similar to this, with more than two lines showing [ellipsis] and a down arrow.
The effect after clicking the down arrow: (Full row expanded)
Implementation plan one: js
The method adopted is to first determine whether the element exceeds two lines. If it exceeds, the first N characters will be intercepted and spliced with an ellipsis for ...
display; no more than two lines will be displayed normally. The method to determine whether the element content exceeds n lines is as follows:
/**
* 工具方法参数类型
*/
export interface MoreThanLineParams {
containerClassName: string; // 父元素类名,需包含字号属性
width: number; // 行宽度
content: string; // 内容
line?: number; // 行数
}
/**
* 判断元素是否超过n行
* 默认两行
*/
export const moreThanLines = ({
containerClassName,
content,
width,
line = 2,
}: MoreThanLineParams) => {
let result = false;
// 用于存放内容的元素
const tempNode = document.createElement('div');
tempNode.setAttribute('id', 'temp-node');
tempNode.style.position = 'absolute';
tempNode.style.visibility = 'hidden';
// 将传递进来的类名和文本内容赋值
tempNode.classList.add(containerClassName);
tempNode.style.width = width + 'px';
tempNode.innerHTML = content;
const containerNode = document.body.appendChild(tempNode);
// 用于计算行高的元素
const dupNode = document.createElement('div');
dupNode.classList.add(containerClassName);
dupNode.style.width = width + 'px';
dupNode.style.wordBreak = 'keep-all';
dupNode.style.overflowWrap = 'normal';
dupNode.style.whiteSpace = 'nowrap';
dupNode.style.position = 'absolute';
dupNode.innerHTML = content.substring(0, 2);
dupNode.setAttribute('id', 'copy-node');
const getLineHeightNode = document.body.appendChild(dupNode);
if (containerNode.offsetHeight > getLineHeightNode.offsetHeight * line) {
result = true;
}
document.body.removeChild(containerNode);
document.body.removeChild(getLineHeightNode);
return result;
};
Reference article:
[CSS text truncation skills] https://zhuanlan.zhihu.com/p/35713421
[CSS to achieve multi-line text expansion and collapse effect] https://github.com/sisterAn/blog/issues/120