背景:
开始在网上找了很多解决方案都感觉不灵活,要么写死高度来判断,要么用文字字数,要么用两个容器重复渲染同样的文本,一直在想一个简单方便的解决方案。
原理:
原理其实很简单,后来发现只要两个容器:
一个父容器来控制文本溢出显示省略号,让父容器默认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 ↑':'Open ↓'}}
</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