前端开发那些事儿Vue实用小技巧

Vue 文本超过三行展示省略号,并加上展开和收起的功能

2020-11-24  本文已影响0人  苍茫的天涯

场景:在vue项目中文本超过三行展示省略号,并加上展开和收起的功能

在处理多行文本时,经常会遇到各种各样的需求,比如至多展示三行,多余的部分不展示并以省略号结尾;又比如在这个基础上加上一个展开和收起的功能。同时UI的展示上还要求和文本本身的位置相对应。

具体实现思路如下:

其中需要注意的点有

下面是我在日常迭代中写的一个比较简单的三行展示省略号并带有展开收起功能的小例子。欢迎大佬们指正~

先上具体实现代码:

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>

Style

<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>

Script

<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>


上一篇下一篇

猜你喜欢

热点阅读