【uni-app】微信小程序如何轻松判断文本溢出显示展开按钮

背景:

开始在网上找了很多解决方案都感觉不灵活,要么写死高度来判断,要么用文字字数,要么用两个容器重复渲染同样的文本,一直在想一个简单方便的解决方案。

原理:

原理其实很简单,后来发现只要两个容器:

一个父容器来控制文本溢出显示省略号,让父容器默认overflow:hidden,一个内联子容器来放文本,文本容器的高度>父容器的高度则说明溢出了

文本溢出:

在这里插入图片描述

展开后:

在这里插入图片描述

文本不溢出时:

在这里插入图片描述

完整代码:

<template>
	<view class="content">
		<view>
			<view class='title-box'>
				<label>content:</label>
				<button type='primary' class="mini-btn" size='mini' v-show="isOverflowed" @click="changeOverflowStatus">
					{{isCollapsed?'Collapse &uarr;':'Open &darr;'}}
				</button>
			</view>
			<view class="text-wrapper" :class="{'not-overflow':isCollapsed}">
				<!-- is overflowed -->
				<!-- <text class="text">
					This is a demo to use a button to control whether it shows the whole content text or show part text with the ellipsis, thanks for my efforts, I make it,I make it,I can make it
				</text> -->
				<!-- not overflowed -->
				<text class="text">
					This is a demo
				</text>	
			</view>	
			
			
		</view>				
	</view>
</template>


<script>
	export default {
		data() {
			return {
				isOverflowed: false,
				isCollapsed: false				
			}
		},
		onLoad() {
			let query = uni.createSelectorQuery();
			let textHeight,wrapperHeight;
			
			query.select(".text-wrapper").boundingClientRect(data=>{
				wrapperHeight = data.height;
			});			
			
			query.select(".text").boundingClientRect(data=>{
				textHeight = data.height;
			});
			
			query.exec(res=>{
				if(textHeight > wrapperHeight){
					this.isOverflowed = true;
				}else{
					this.isOverflowed = false;
				}				
			});



		},
		methods: {
			changeOverflowStatus(){
				this.isCollapsed = !this.isCollapsed;
			},			
		}
	}
</script>

<style scoped lang='scss'>
	.content {
		padding: 25rpx;
	}	
	.title-box {
		display: flex;
		.mini-btn {
			margin-left: auto;
			margin-right: 0;
		}
	}
	.text-wrapper {
		font-size: 30rpx;
		margin-top: 30rpx;
		display:-webkit-box;
		-webkit-line-clamp:2;
		-webkit-box-orient:vertical;
		overflow:hidden;
		
		&.not-overflow {
			-webkit-line-clamp: unset;
			overflow: auto;
		}		
	}

</style>

项目源代码已上传github仓库:https://github.com/AdelinaPeng/ellipsis-explore.git

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值