css版本 :
.multi-row {
display: -webkit-box;
overflow: hidden;
white-space: normal !important;
text-overflow: ellipsis;
/* autoprefixer: off */
word-wrap: break-word;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
但是我们在日常开发中,有时候需求超过三行不是展示“...” 而是其他文字,例如: more , 更多... 更多文字,这时候需要js去计算了,css是无法满足的。
js(react ):
思路:
1.计算文本高度
2.计算文本lineHeight
3.如果 文本高度 >文本lineHeight* 行数
(1) className ='multi-row' 文本超过三行
(2) 显示 more 或者 更多...
const multiRow = useRef(null);
const [showDescription, setShowDescription] = useState(false);
const [needMore, setNeedMore] = useState(false);
useEffect(() => {
const height = parseInt(getComputedStyle(multiRow.current).height);
const lineHeight = parseInt(getComputedStyle(multiRow.current).lineHeight);
if (height > (lineHeight * 3)) {
setShowDescription(true)
setNeedMore(true)
}
}, [])
html
<div className={showDescription ? 'multi-row' : 'break-all'}
ref={multiRow}
dangerouslySetInnerHTML={{ __html: description.replace(/(rn|n|r)/gm, "<br/>") }}>
</div>
{needMore ?
<span
className='button red'
onClick={() => {
setShowDescription(!showDescription)
}} >more</span> : null}