1、超过3行显示省略号和更多按钮,不超过3行正常显示;
html:
<div class="container"><div style="display: flex;"><div class="content"><div class="text-content" ref="textContentRef">{{ 文本内容文本内容文本内容文本内容文本内容文本内容文本内容文本内容 || '-' }}</div></div><div class="btn"></div></div> </div>
js:
javascript">mounted () {this.$nextTick(() => {setTimeout(() => { // 一定要加定时器,不然拿不到文本高度this.handleResume()}, 500);})
}
handleResume () {const maxHeight = 54 // 3行的高度,可以根据实际情况调整const btn = document.querySelector('.btn')const content = document.querySelector('.content')const textContent = document.querySelector('.text-content')const textHeight = textContent.getBoundingClientRect().height // 文本高度const contentHeight = content.getBoundingClientRect().height // 容器高度// console.log(textHeight,'textHeight----');// console.log(maxHeight,'maxHeight------');btn.innerHTML = '...更多'let flag = falseif (textHeight <= maxHeight) {// btn.innerHTML = ''btn.style.display = 'none'} else {btn.style.display = 'block'}btn.addEventListener('click', () => {if (!flag) {content.style.maxHeight = textHeight+'px' // 铺开展示btn.innerHTML = '收起'flag = true} else {content.style.maxHeight = contentHeight+'px' // 铺开展示btn.innerHTML = '...展开'flag = false}})
},
css:
.container {position: relative;
}
.content {max-height: 54px;overflow: hidden;transition: max-height 0.5s;}
.text-content {font-size: 14px;line-height: 18px;
}
.btn {position: absolute;right: 0;bottom: 2px;background: linear-gradient(to right, rgba(255,255,255,0.2), #fff 35%);padding-left: 25px;color: #409eff;cursor: pointer;font-size: 14px;
}
效果图:
超过3行:
没超过3行: