小程序组件封装
设置行高,2行多高换算成px,这里组件是5行换算成px是126,渲染后获取元素高度判断是否超出,超出增加对应样式和控制显示展开按钮
wx.js
import random from 'lodash.random';
Component({
options: { addGlobalClass: true },
properties: {
text: String,
},
data: {
showExpande: false,
ellipsis: false,
id: '',
},
lifetimes: {
ready() {
if (this.data.text) {
this.init();
}
},
},
methods: {
onToggle() {
this.setData({ ellipsis: !this.data.ellipsis });
},
init() {
this.setData({ id: 'content' + Date.now() + random(100000, 999999).toString() }, () => {
const query = wx.createSelectorQuery().in(this);
query.select(`#${this.data.id}`).boundingClientRect((res) => {
const showExpande = res?.height > 126;
this.setData({ showExpande });
}).exec();
});
},
},
});
wx.wxml
<view wx:if="{{text}}" class="act-detail_intro border-box pd-20 mt-40 radius-24 flex-column">
<view class="font-28 {{!ellipsis ? 'ellipsis-5' : ''}}">
<text id="{{id}}" decode space>{{text}}</text>
</view>
<view class="fold_btn width-full flex-end font-28" bindtap="onToggle" wx:if="{{showExpande}}">{{!ellipsis ? '展开' : '收起'}}</view>
</view>
wx.wxss
.act-detail_intro {
background: rgba(255, 255, 255, 0.2);
font-weight: 400;
color: #ffffff;
line-height: 42rpx;
}
.act-detail_intro .fold_btn {
font-weight: 400;
line-height: 42rpx;
color: rgba(255, 255, 255, 0.2);
}
.ellipsis-5 {
display: -webkit-box;
-webkit-box-orient: vertical;
text-overflow: -o-ellipsis-lastline;
overflow: hidden;
text-overflow: ellipsis;
-webkit-line-clamp: 5;
line-clamp: 5;
}
wx.json
{
"component": true,
"usingComponents": {}
}