1.html
<div class="dp-text-ellipsis-wrapper" v-if="isfollow">
<div class="text" ref="text">
<label
class="btn1"
@click="isfollow = !isfollow"
>收起
<i
class="el-icon-arrow-right el-icon--right"
></i
></label>
{{ content }}
</div>
</div>
<div class="dp-text-ellipsis-wrapper" v-if="!isfollow">
<div
class="text"
:style="textStyleObject"
ref="text"
>
<label
class="btn"
v-if="contentWidth > allWidth"
@click="isfollow = !isfollow"
>查看全部
<i
class="el-icon-arrow-right el-icon--right"
></i
></label>
{{ content }}
</div>
</div>
2.js
<script>
data() {
return this.mixinsInit({
content:'',
allWidth: 0,
contentWidth: 0,
isfollow: false,
})
},
computed: {
textStyleObject() {
return {
// 设置两行折叠2*2,三行折叠2*3
'max-height': `${2 * 2}em `,
}
},
},
mounted() {
//此处需要获取当前文本盒子的长度,上面html没有写这个盒子 自行设定
let className = document.getElementById('box')
this.allWidth = className.offsetWidth
// 此处获取文字长度
this.contentWidth = this.getLenPx(
content
)
},
methods:{
getLenPx(str) {
let str_leng = str.replace(/[^\x00-\xff]/gi, 'aa').length // eslint-disable-line
return (str_leng * 16) / 4
},
}
</script>
3.css
.dp-text-ellipsis-wrapper {
display: flex;
overflow: hidden;
font-size: 14px;
line-height: 20px;
.text {
position: relative;
overflow: hidden;
line-height: 2.1;
line-height: 30px;
text-align: justify;
text-overflow: ellipsis;
word-break: break-all;
}
.text::before {
float: right;
height: calc(100% - 20px);
content: '';
}
.btn {
position: relative;
float: right;
clear: both;
margin-left: 10px;
font-size: 12px;
padding: 0 8px;
color: #206ef7;
line-height: 20px;
border-radius: 4px;
cursor: pointer;
z-index: 10;
}
.btn1 {
position: absolute;
bottom: 2px;
right: 0;
color: #206ef7;
cursor: pointer;
font-size: 12px;
}
.btn::before {
position: absolute;
left: 1px;
color: #333;
transform: translateX(-100%);
content: '...';
}
}