之前寫過一篇《微信小程序:text文本的展開與收起》,通過css控制最大顯示行數(shù),后來不少人私信問如果不足三行如何自動隱藏“展開/收起”按鈕;我接觸這個時(shí)間比較短,也不太熟悉,暫時(shí)只能想到改為js控制文字長度來處理。
h5 ellipsis.gif
js
js主要定義了四個變量:完整內(nèi)容content,顯示的內(nèi)容contentShow,收起時(shí)最大顯示文字長度maxLength,是否收起ellipsis
然后定義了“展開/收起”按鈕的點(diǎn)擊觸發(fā)事件ellipsis。
/* js */
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
content: "1. 博客 itlao5.com\n2. 簡書 ThinkinLiu", // 完整的內(nèi)容
contentShow: "1. 博客 i", // 真實(shí)顯示的內(nèi)容
maxLength: 10, // 收起時(shí)最大顯示文字長度
ellipsis: true, // 是否收縮
},
ellipsis: function () {
var ellipsis = !this.data.ellipsis;
var contentShow = this.data.content;
var maxLength = this.data.maxLength;
// 如果內(nèi)容長度少于10,則不截取;否則當(dāng)處于收起狀態(tài),截取7個文字并加上省略號
contentShow = (contentShow.length > maxLength && ellipsis) ? contentShow.substring(0, maxLength - 3) + "..." : contentShow;
this.setData({
contentShow: contentShow,
ellipsis: ellipsis
})
},
})
wxml
wxml很簡單,一個用于展示內(nèi)容的text,一個展開/隱藏 按鈕,需要注意點(diǎn)是hidden='{{content.length<=maxLength}}',即當(dāng)文字小于指定長度時(shí),隱藏該按鈕
/* wxml */
<view class='bg-white vertical'>
<text class="pay-hint-content" >{{contentShow}}</text>
<text class='ellipsis_text' hidden='{{content.length<=maxLength}}' bindtap='ellipsis'>{{ellipsis?"展開":"收起"}}</text>
</view>
wxss
最后,提供下wxml中用到的wxss
/* wxss */
.bg-white{
width: 100%;
display: flex;
flex-direction: row;
background-color: white;
}
.vertical {
display: flex;
flex-direction: column;
}
.pay-hint-content{
margin-left: 5%;
margin-right: 5%;
margin-top: 10px;
font-size: 16px;
color: #888;
display: -webkit-box;
text-overflow: ellipsis;
-webkit-box-orient:vertical;
overflow:hidden;
}
.ellipsis_text{
width: 100%;
font: 16px;
text-align: center
}
個人博客: IT老五
微信公眾號:【IT老五(it-lao5)】,一起源創(chuàng),一起學(xué)習(xí)!
ps:與《微信小程序:text文本的展開與收起》不同,本文方法使通過js控制文本長度,有點(diǎn)是可以實(shí)現(xiàn)不足指定文字長度自動隱藏“展開/收起”按鈕,不足之處是中英文文字長度不同,以及不同屏幕一行可以顯示的文字長度不同,導(dǎo)致會出現(xiàn)文字一行顯示不完整的情況。實(shí)際中可以根據(jù)需求來選擇使用哪種方式,或者可以綜合兩種方式,少于N字隱藏按鈕,收起與隱藏根據(jù)css實(shí)現(xiàn)。