C V大法:Vue2 使用纯CSS 实现多行文本的“展开“ 和 ”收起” 功能

962 阅读1分钟

CV.jpg

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

C V 系列特点:

  1. 只关注功能的实现。让各位看官复制粘贴即可安心使用
  2. 代码注释会写详细,尽可能做到一行一注释,把细节都说清楚
  3. 涉及第三方库等等不做赘述,用到的库会给各位看官放上的链接的,方便各位深入了解

功能演示

text.gif

话不多说 上代码

这就是一个.vue文件 我这里抽离成了一个组件

html

<template>
    <div class="mj-text-hide">
        <input id="group-members_exp" type="checkbox" />
        <!-- theBackground 给more-text元素 设置上css变量 -->
        <div class="more-text" :style="theBackground">
            <label class="more-btn cur" for="group-members_exp">
                <span class="text"></span>
                <i class="el-icon-arrow-down"></i>
            </label>
            {{ value }}
        </div>
    </div>
</template>

js

<script>
export default {
    name: 'MjTextHide',
    props: {
        value: { // 文字
            type: String,
            default: ''
        },
        theBackgroundColor: { // 文字伪类背景颜色
            type: String,
            default: '#f9f9f9'
        }
    },
    data() {
        return {
            theBackground: {
                // css 变量
                '--the-background-color': this.theBackgroundColor
            }
        }
    }
}
</script>

css

<style scoped lang="scss">
.mj-text-hide {
    display: flex;

    .more-text {
        overflow: hidden;
        line-height: 1.5;
        max-height: 21px;
        position: relative;

        &::before {
            content: '';
            float: right;
            width: 0;
            height: calc(100% - 20px);
            /*100%减去一个按钮的高度即可*/
            background: var(--the-background-color);
        }

        &::after {
            content: '';
            width: 100%;
            height: 100%;
            position: absolute;
            background: var(--the-background-color);
        }

        .more-btn {
            float: right;
            clear: both;
            color: #000;

            &::before {
                content: '…';
                margin-right: 15px;
                color: #000;
                font-size: 14px;
                transform: translateX(-100%);
            }

            .text::after {
                content: '展开';
            }
        }
    }

    #group-members_exp {
        display: none;

        &:checked + .more-text {
            -webkit-line-clamp: 999;
            max-height: none;
        }

        &:checked + .more-text .more-btn .text::after {
            content: '收起';
        }

        &:checked + .more-text .more-btn .el-icon-arrow-down {
            transform: rotate(180deg);
        }

        &:checked + .more-text .more-btn::before {
            display: none;
        }

        &:checked + .more-text::after {
            display: none;
        }
    }
}
</style>

总结

  1. 因为要做成一个组件使用,就要保证在不同的背景颜色下不出现异常,所以我这里使用了css变量。
  2. 若是不考虑做成组件就不需要使用css变量了。不做作组件的话,也可以考虑抽离css。使用scss函数也可以做到改变背景颜色。😀

实现思路借鉴于 CSS 实现多行文本“展开收起”

欢迎查看更多C V系列 C V 大法