微信小程序文字段落展开收起组件

实现原理:

  1. 计算每行高度
  2. 文字段落总高度除以每行高度得出总共多少行可以显示完成
  3. js设置初始显示的高度(行数*每行高度=初始高度)

引用方法:

1
<spread-text out-class="movie-review" show-num="6" text="{{detail.movie_review}}"></spread-text>

源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// spread-text.json
{
"component": true
}

// spread-text.wxml
<view class="box">
<view id="J-text" class="component spread-text out-class" style="{{textStyle}}">
{{text}}
</view>
<view class="toggle" id="J-toggle" catchtap="toggleHandler" style="display: {{showToggle}}">
<image class="arrow {{toggleText}}" src="../../images/arrow.png"></image>
</view>
<view id="J-placeholder" class="out-class" style="display: {{showPlaceholder}};">测试</view>
</view>

// spread-text.wxss
:host {
font-size: 30rpx;
color: #333;
}

.box {
position: relative;
}

.spread-text {
opacity: 0;
height: auto;
word-wrap: break-word;
transition: all 100ms linear 0s;
}

.toggle {
display: flex;
align-items: center;
justify-content: center;
height: 46rpx;
}

.toggle image {
width: 22rpx;
height: 14rpx;
}

.toggle .arrow.up {
transform: rotateZ(180deg);
}

// spread-text.js
Component({
externalClasses: ['out-class'],
properties: {
text: String,
showNum: {
type: Number,
value: 3
}
},
data: {
showPlaceholder: 'block',
textStyle: '',
toggleText: 'down',
showToggle: 'none'
},
methods: {
toggleHandler() {
if (this.data.toggleText === 'down') {
this.setData({
toggleText: 'up',
textStyle: `height: ${
this.textHeight
}px; opacity: 1; overflow: hidden;`
});
} else {
this.setData({
toggleText: 'down',
textStyle: `height: ${this.showH}px; opacity: 1; overflow: hidden;`
});
}
}
},
ready() {
const query = wx.createSelectorQuery().in(this);

query.select('#J-text').boundingClientRect();
query.select('#J-placeholder').boundingClientRect();

query.exec(res => {
const textElement = res[0];
const placeholderEelement = res[1];

const textHeight = textElement.height;
const placeholderHeight = parseInt(placeholderEelement.height, 10);

this.showH = placeholderHeight * this.data.showNum;
this.textHeight = textHeight;

if (this.showH < textHeight) {
this.setData({
showToggle: 'flex',
showPlaceholder: 'none',
textStyle: `height: ${this.showH}px; opacity: 1; overflow: hidden;`
});
} else {
this.setData({
showToggle: 'none',
showPlaceholder: 'none',
textStyle: `height: ${
this.textHeight
}px; opacity: 1; overflow: hidden;`
});
}
});
}
});