超过两行省略且尾部添加图标:
js判断是一行还是两行:
const { postData } = props;
useEffect(() => {
const titleDoms = Array.from(document.querySelectorAll('.search-result-title') || [])
titleDoms.forEach(item => {
const style = window.getComputedStyle(item);
const height = parseInt(style.height);
const lineHeight = parseInt(style.lineHeight);
if (height / lineHeight > 1) {
item.classList.add(styles['line2'])
} else {
item.classList.add(styles['line1'])
}
})
},[postData])
Html结构:
<div className={styles['content-wrapper']}>
<div className='search-result-title'>
{item.isNews ? <img className={styles['icon-1']} src={message} /> : null}
<span className={styles['title']} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(item.title) }}></span>
{item.isNews ? <img className={styles['icon-2']} src={message} /> : null}
</div>
</div>
css样式:
.content-wrapper {
max-width: 100%;
position: relative;
.hupu-font-title2;
.word('PingFangSC-Regular, PingFang SC',400);
margin-bottom: 8px;
.more-n-hidden(2);
word-break: break-all;
}
/*撑开高度,确保icon-1位于文本右下方,文本超出时*/
.line2::before {
content: '';
display: block;
float: right;
width: 0;
height:26px;
}
.line1::before {
content: '';
display: block;
float: right;
width: 0px;
height:0;
}
/*用于文本未超出时遮挡icon-1,文本未超出时*/
.line1::after,.line2::after {
position: absolute;
content: '';
display: inline-block;
width: 100%;
height: 100%;
background: var(--bg);
}
/*文本超出后显示的图标*/
.icon-1 {
height: 16px;
width: 26px;
margin-left: 3px;// 解决省略号和资讯重叠
float: right;
clear: both;
display: block;
}
/*文本未超出时显示的图标*/
.icon-2 {
height: 16px;
width: 26px;
margin-left: 3px;// 解决省略号和资讯重叠
vertical-align: baseline;
}