uniapp开始小程序判断文本的行数文本高度显示展开
比如:在显示一段“描述”文本时,文本的行数可能因为不同的字符(英文或中文)而无法确定。这时可通过判断该区域的高度来决定是否显示‘展开’按钮。
代码:
<template>
<view class="container">
<view class="content" ref="contentRef">
<!-- 这里是你的文本内容 -->
{{ yourText }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
yourText: '这里是你的文本内容'
};
},
mounted() {
this.$nextTick(() => {
this.checkTextLines();
});
},
methods: {
checkTextLines() {
// 获取 <div> 标签的节点信息
const query = uni.createSelectorQuery().in(this);
query.select('.content').boundingClientRect(data => {
// 获取文本内容的高度
const height = data.height;
// 假设行高为20px
const lineHeight = 20;
// 计算文本行数
const lines = Math.ceil(height / lineHeight);
// 判断文本行数是否达到了3行
if (lines >= 3) {
console.log("文本达到了3行或以上");
} else {
console.log("文本没有达到3行");
}
}).exec();
}
}
}
</script>
<style scoped>
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.content {
width: 200px; /* 设置文本容器的宽度 */
overflow: hidden; /* 文本超出部分隐藏 */
white-space: pre-wrap; /* 允许文本换行 */
}
</style>