这是一个Uniapp插件,项目实例地址:uniapp-文本缩略显示&img自适应
<template>
<view class="relative text_conts" ref="boxWrap">
<!-- 文本超出展示 “全文” -->
<view v-if="overflow" :class="!isOpen?'':''" :style="wrapStyle">
<text>{{ !isOpen? txt_val+'......' : text }}</text>
<block v-if="showMore && overflow">
<text v-if="!isOpen" @tap="toggleShowMore" class="c-theme pd-l-15">{{ showLabel }}</text>
</block>
</view>
<view v-else>
<rich-text :nodes="text" class="pre_wrap" :style="wrapStyle"></rich-text>
</view>
<view class="t-r c-99" v-if="isOpen && opened" @tap="toggleShowMore">{{ shrinkLabel }}</view>
</view>
</template>
<script>
/**
* TextEllipsis 文本缩略/展开
* @description 此组件一般用于内容缩略显示和展开
* @property {Number} lineClamp 显示行数,超过则缩略显示
* @example <text-ellipsis>默认超过三行缩略显示</text-ellipsis>
*/
export default {
name: 'TextEllipsis',
props: {
// 展示文本
text: {
type: String,
default: ''
},
// 显示行数
lineClamp: {
type: Number,
default: 3
},
// 字体大小
fontSize: {
type: String,
default: '26rpx'
},
// 行高(单位rpx)
lineHeight: {
type: Number,
default: 34
},
// 显示`全文`字眼
showMore: {
type: Boolean,
default: true
},
// 全文展示文本
showMoreLabel: {
type: String,
default: '全文'
},
// 显示`收起`字眼
showShrink: {
type: Boolean,
default: true
},
// 收起文本
shrinkLabel: {
type: String,
default: '收起'
}
},
data() {
return {
txt_val: '',
txt_status: false,
overflow: false, // 文本是否溢出
isOpen: false, // 当前是否展开
opened: false, // 是否展开过
calculated: false // 计算过高度是否溢出
};
},
computed: {
wrapStyle() {
const { lineClamp, lineHeight, fontSize, isOpen, calculated } = this;
const multiline = lineClamp > 1;
const result = {
lineClamp,
fontSize,
lineHeight: `${lineHeight}rpx`,
whiteSpace: multiline ? 'wrap' : 'nowrap'
};
if (multiline && !isOpen && calculated) {
result.display = '-webkit-box';
}
return result;
},
showLabel() {
const { showMore, overflow, isOpen, showMoreLabel, shrinkLabel } = this;
return showMore && overflow && !isOpen ? showMoreLabel : shrinkLabel;
}
},
created() {
this.txt_val = this.text.substring(0, 69);
},
mounted() { this.setShowMore(); },
updated() { this.setShowMore(); },
methods: {
async setShowMore() {
await this.$nextTick();
const query = uni.createSelectorQuery().in(this);
query.select('.text_conts').boundingClientRect(data => {
// 文本内容高度是否超过 显示行数*行高(单位px)
const isOver = data.height > this.lineClamp * (this.lineHeight / 2);
if (isOver && !this.overflow) { this.overflow = true; }
this.calculated = true;
})
.exec();
},
toggleShowMore() {
this.isOpen = !this.isOpen;
this.opened = true;
}
}
};
</script>
<style lang="scss" scoped>
</style>
用法:
<text-ellipsis :text='a.content' fontSize="28rpx" :txtshow="false"></text-ellipsis>
rich-text 富文本--换行问题
<rich-text :nodes="info.content|formatRichText" style="white-space: pre-line;"></rich-text>