虽说简单 平时遇到的情况挺多的 还是整一个~ 通过 vue
实现组件
<template>
<div
:class="{ sug: true, close: infoLength > 1 && !more }"
:style="{ paddingRight: more ? '0' : '35px' }"
>
<span ref="tv">{{ text }}</span>
<span
:class="{ expand: true, absolute: !more }"
v-if="infoLength > 1"
@click="lookMore"
>
{{ more ? "折叠" : "展开" }}
</span>
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
default: "-"
}
},
data() {
return {
infoLength: "",
more: false
};
},
watch: {
async text(newValue, oldValue) {
await this.$nextTick();
let res = this.$refs.tv.getClientRects();
console.log("watch tv getClientRects() is ", res);
}
},
mounted() {
let res = this.$refs.tv.getClientRects();
this.infoLength = res.length;
},
methods: {
lookMore() {
this.more = !this.more;
}
}
};
</script>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
@import "~@/styles/variables.scss";
@import "~@/assets/scss/analyze.scss";
.sug {
position: relative;
.absolute {
position: absolute;
top: 0;
right: 4px;
}
}
.expand {
color: $menuActiveText;
cursor: pointer;
}
.close {
overflow: hidden; //超出部分隐藏
text-overflow: ellipsis; //当对象内文本溢出时显示省略标记(...)
display: -webkit-box; //弹性伸缩盒子模型显示
-webkit-box-orient: vertical; // 甚至伸缩盒对象的子元素排列方式
-webkit-line-clamp: 1; // 限制一个块元素显示文本的行数
}
</style>
核心其实就是 getClientRects
判断行数 比我想的简单 以为需要像iOS
那样去计算文字高度