uniapp text展开收起

2023-07-13  本文已影响0人  倪大头

通过line-height和max-height控制行数
通过伪元素和float把展开按钮定位在文本右下角
通过boundingClientRect获取文本总行数,来判断是否需要展开按钮

expandable_text.vue组件完整代码:

<template>
    <view class="container"
        :style="{ '--font-size': fontSize + 'rpx', '--text-color': textColor, '--show-ellipsis': expand ? 'hidden' : 'visible' }">
        <view id="info" class="info-label" :style="{ maxHeight: expand ? 'none' : 1.5 * maxLine + 'em' }">
            <text v-if="showBtn" class="expand-label" @click.stop="onClickExpand">{{ expand ? '收起' : '展开' }}</text>
            {{ text }}
        </view>
    </view>
</template>

<script>
    export default {
        props: {
            // 文本
            text: {
                type: String,
                default: ''
            },
            // 字号
            fontSize: {
                type: Number,
                default: 28
            },
            // 文字颜色
            textColor: {
                type: String,
                default: '#333'
            },
            // 收起时最大行数
            maxLine: {
                type: Number,
                default: 1,
            }
        },
        data() {
            return {
                showBtn: false, // 是否显示展开按钮
                expand: false, // 文字是否展开
            }
        },
        mounted() {
            uni.createSelectorQuery().in(this).select('#info').boundingClientRect(rect => {
                // 文字行数
                let lineCount = parseInt(rect.height / uni.upx2px(this.fontSize))
                this.showBtn = lineCount > this.maxLine
                console.log(`行数:${lineCount} ${this.showBtn}`)
            }).exec()
        },
        methods: {
            // 展开/收起
            onClickExpand() {
                this.expand = !this.expand
            }
        }
    }
</script>

<style scoped>
    .container {
        display: flex;
    }

    .info-label {
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        line-height: 1.5;
        text-align: justify;
        font-size: var(--font-size);
        color: var(--text-color);
    }

    .info-label::before {
        content: '';
        float: right;
        width: 0;
        height: 100%;
        margin-bottom: calc(var(--font-size) * -1.5);
    }

    .expand-label {
        float: right;
        clear: both;
        color: dodgerblue;
    }

    .expand-label::before {
        content: '...';
        color: var(--text-color);
        visibility: var(--show-ellipsis);
    }
</style>

使用方法:
text:文本字符串
fontSize:文本字号,int类型
textColor:文本颜色,string类型
maxLine:文本收起时最大行数,int类型

<ExpandableText :text="text" :fontSize="28" :maxLine="2"></ExpandableText>

效果:


image.png image.png
上一篇 下一篇

猜你喜欢

热点阅读