uniapp 小程序 CSS 实现多行文本展开收起 组件
效果
组件
<template><!-- 最外层弹性盒子 --><div class="box" :style="boxStyle"><!-- 文本区域,动态类名控制展开/收起状态 --><div ref="textRef" :class="['text-cont', btnFlag ? 'text-unfold' : 'text-collapse']"><!-- 展开/收起按钮 --><div class="unfold-and-collapse" @click="btnFlagChange">{{ btnFlag ? '收起' : '展开' }}</div><!-- 文本内容(保留首行缩进) -->  {{ text }}</div></div>
</template><script>export default {name: 'ExpandableText',props: {text: {type: String,default: ''},boxStyle: {type: String,default: ''}},data() {return {// 展开收起状态btnFlag: false}},methods: {// 切换展开/收起状态 btnFlagChange() {this.btnFlag = !this.btnFlag}}}
</script><style scoped>/* 最外层开启弹性盒子,用于伪元素的高度计算 */.box {display: flex;}/* 文本区域设置宽度,显示省略号 */.text-cont {width: 100%;margin: 0px auto 0;display: -webkit-box;/* 必须结合的属性,设置或检索伸缩盒对象的子元素的排列方式 */-webkit-box-orient: vertical;/* 溢出部分隐藏 */overflow: hidden;/* 文字居左 */text-align: left;font-family: PingFangSC, PingFang SC;font-weight: 500;font-size: 26rpx;color: #000000;line-height: 44rpx;font-style: normal;}/* 展开状态 - 显示所有行 */.text-unfold {-webkit-line-clamp: 9999;}/* 收起状态 - 只显示3行 */.text-collapse {-webkit-line-clamp: 3;}/* 展开/收起按钮样式 */.unfold-and-collapse {color: #19aaff;float: right;clear: both;margin-right: 10px;cursor: pointer;font-size: 26rpx;line-height: 44rpx;margin-top: -6rpx;}/* 伪元素用于实现文字包裹按钮 */.text-cont::before {content: "";float: right;width: 0;height: calc(100% - 20px);}
</style>