1. 效果圖
-
收起狀態
-
展開狀態
2. 代碼實現
<view class="word-wrap" id="descriptionTxt"><view class="fold-text" v-if="isFold"><text class="fold-btn" @click="changFold">全文</text><text>{{ describe || '' }}</text></view><view class="unfold-text" v-if="!isFold"><text>{{ describe || '' }}</text><text v-if="showFold" style="color: #bdc1c5; float: right; margin-left: 10rpx" @click="changFold">收起</text></view>
</view>
data: {return {describe: '', // 動態獲取文本內容showFold: false, // 是否展示全文/收起isFold: false, // 右下角文字:true-全文 false-收起}
}methods: {// 判斷文本是否超過五行,默認展開checkTextLines() {const query = uni.createSelectorQuery().in(this)query.select('#descriptionTxt').boundingClientRect(res => {// 獲取文本內容的高度const contentHeight = res.heightconst lineHeight = rpxTopx(46) // 文字的行高const lines = Math.ceil(contentHeight / lineHeight)// 判斷文本行數是否達到了5行if (lines > 5) {this.showFold = true} else {this.showFold = false}}).exec()},// 切換展開/收起changFold() {this.isFold = !this.isFold}
}
.word-wrap {display: flex;// 收起狀態.fold-text {font-size: 28rpx;color: #484848;line-height: 46rpx;text-align: justify;word-break: break-all;line-break: anywhere;white-space: pre-wrap;display: -webkit-box;overflow: hidden;-webkit-line-clamp: 5;-webkit-box-orient: vertical;}.fold-text::before {content: '';float: right;width: 0;/* 用整個容器高度減去按鈕的高度,發現高度失效了,這里需要給 .fold-text 包裹一層,然后設置 display: flex *//* height: calc(100% - 46rpx); *//* 或者用margin負值來實現(性能會比 calc 略好一點) */height: 100%;margin-bottom: -46rpx;}.fold-btn {color: #bdc1c5;float: right;clear: both;margin-left: 10rpx;}// 未收起狀態.unfold-text {font-size: 28rpx;color: #484848;line-height: 46rpx;text-align: justify;word-break: break-all;line-break: anywhere;white-space: pre-wrap;}
}
經測試:部分機型會有bug,后面就沒用這種方法了,不知道大家有沒有更好的方法實現這種效果,歡迎留言~。
具體原理請參考大佬文章:前端實現超出文字顯示展開收起的功能