文本溢出时,显示“展开--收起”
2023-07-02 本文已影响0人
郭_小青
需求:文本超出4行以后,显示展开--收起按钮。例子中使用的v-html
image.png
效果:
1、默认显示样式
2、点击展开后效果 image.png
vue文件实现代码
export default({
data(){
return {
infoScrollHeit: 0, //文本区域包含滚动条高度
infoClientHeit: 0, //文本区域不包含滚动条高度
},
mounted(){
this.infoScrollHeit = this.$refs.info.scrollHeight
this.infoClientHeit = this.$refs.info.clientHeight
// 一下代码可以将文本还原为:默认显示状态
// if(this.$refs.exp2.checked) {
// this. infoClientHeit = 80 //4行文本的高度为80px
// this.$refs.exp2.checked = false
//}
}
}
})
<div class="wrapper">
<input id="exp2" ref="exp2" class="exp" type="checkbox">
<div class="text">
<label v-if="infoScrollHeit > infoClientHeit" class="btn" for="exp2"></label>
<div ref='info' v-html="info"></div>
</div>
</div>
css文件实现代码
.wrapper {
padding: 8px;
background: #FEF8E7;
border-radius: 2px;
display: flex;
overflow: hidden;
}
.text {
font-size: 12px;
line-height: 20px;
font-weight: 400;
color: #FF9505;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
position: relative;
width: 100%;
}
.text::before {
content: '';
height: calc(100% - 20px);
float: right;
}
.text::after {
content: '';
width: 999vw;
height: 999vw;
position: absolute;
box-shadow: inset calc(100px - 999vw) calc(30px - 999vw) 0 0 #FEF8E7;
margin-left: -100px;
}
.btn{
font-size: 12px;
line-height: 20px;
font-weight: 400;
color: #2B6DE5;
float: right;
clear: both;
cursor: pointer;
/* margin-top: -30px; */
}
.btn::before{
content:'展开'
}
.exp{
display: none;
}
.exp:checked+.text{
-webkit-line-clamp: 999;
transition: all .3s ease-in-out;
}
.exp:checked+.text::after{
visibility: hidden;
}
.exp:checked+.text .btn::before{
content:'收起'
}
借用复选框的功能实现,点击展开+收起的功能。scrollHeight > clientHeight说明文本溢出
以下代码可以将展开的文本还原为:默认显示状态
if(this.$refs.exp2.checked) {
this. infoClientHeit = 80 //4行文本的高度为80px
this.$refs.exp2.checked = false
}
image.png
image.png