具体实现思路如下:
-
- 判断当前内容是否超过三行。此处可以给每行设置一个行高line-height,渲染完后超过三倍的行高即认为是内容超过了三行。
-
- 展示/收起状态的切换可以通过data中的参数来绑定
-
- 在底部使用position:absolute来绝对定位展开该在的位置。
-
- 根据业务需求来设定好展开和收起按钮需要呆的地方。 注:
- 展开收起按钮的高度和行高要和原来文本的行高一致,不然会导致样式不统一。
- 获取文本的高度时要注意使用
this.$nextTick()
来保证DOM渲染完成后再获取高度 - 在不同场景下省略号可能不能够完全遮住最后几个字,可以通过调节空格,字体排布方式等办法来调整,或者不要把展开和文本放在同一行,另起一行并且在末尾打开的样式
DOM
<template>
<div class="content-wrap">
<div :class="['content', expande ? 'expande' : 'close']" ref="content">
思路:1、判断当前内容是否超过三行。此处可以给每行设置一个行高line-height,渲染完后超过三倍的行高即认为是内容超过了三行。2、展示/收起状态的切换可以通过data中的参数来绑定。3、在底部使用position:absolute来绝对定位展开该在的位置。4、根据业务需求来设定好展开和收起按钮需要呆的地方。
</div>
<div
class="expande-button-wrap"
v-if="needShowExpande"
>
<div class="expande-button" @click="expandeClick" v-if="!expande">
<span style="color: black">...</span> 展开
</div>
<div class="expande-button" @click="expandeClick" v-else>收起</div>
</div>
</div>
</template>
Script
<script>
export default {
name: 'App',
data() {
return {
expande: true,
needShowExpande: false,
}
},
methods: {
expandeClick() {
console.log('expandeClick')
this.expande = !this.expande
},
},
mounted() {
this.$nextTick(() => {
let lineHeight = 22
if (this.$refs.content.offsetHeight > lineHeight * 3) {
this.expande = false
this.needShowExpande = true
} else {
this.expande = true
}
})
},
}
</script>
Style
<style >
.content {
font-size: 14px;
color: black;
letter-spacing: 0;
line-height: 22px;
text-align: justify;
overflow: hidden;
/* display: -webkit-box; */
/* -webkit-line-clamp: 3;
-webkit-box-orient: vertical; */
/* text-overflow: ellipsis; */
}
.expande {
overflow: auto;
height: auto;
padding-bottom: 22px;
}
.close {
overflow: hidden;
height: 66px;
padding-bottom: 0;
}
.expande-button-wrap {
position: absolute;
bottom: 0;
right: 0;
height: 22px;
background: white;
}
.expande-button {
text-align: right;
vertical-align: middle;
color: #5995ef;
font-size: 14px;
line-height: 22px;
}
</style>