js显示word_js (react )超过三行展示more

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}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值