文本的展开收起是我们网页常常需要优化处理的操作
需求描述:文本内容若一行能够展示完,则不需要更多/收起按钮;若不能则需单行文本省略展示并显示更多/收起按钮可供操作
html代码段:
<div class="stu-con" >
<div :class="showMore? 'oneLine' : 'allLine'" >
{{ specialInfoData.description }}
</div>
<span
style="width: 70px;margin-left:10px;"
@click="handleShowMore"
id="more"
v-if="showMoreBtn"
>
{{ showMore ? '更多' : '收起'}}
<i :class="{'qw-icon-arrow-down': showMore, 'qw-icon-arrow-top': !showMore}" />
</span>
</div>
js代码段
data () {
return {
showMore: false, // 控制更多/收起按钮的切换
showMoreBtn: false, // 控制更多/收起按钮的展示和隐藏
}
},
methods: {
// 计算字符数
byteCount(str) {
const count = (str && str.replace(/[^\x00-\xff]/g, "xx").length) || 0;
return count;
},
// 更多/收起按钮的切换
handleShowMore() {
this.showMore= !this.showMore
},
getSpecialInfo () {
getSpecialInfo({ id: this.id }, data => {
this.specialInfoData = data.specialInfo || {}
// 对需要展示的文本进行字符长度判断处理
if(this.byteCount(this.specialInfoData.description) > 150) {
this.showMore = true
this.showMoreBtn = true
} else {
this.showMoreBtn = false
}
})
},
}
css代码:
.oneLine {
width: 640px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.allLine {
max-width: 640px;
height: auto;
}