思路:
主要是css上可以分为两部分,第一部分展示前面两行,第二部分会根据第一部分的行数判断缩进的大小,然后展示第三行。最后通过背景色的控制让两者看上去是一段文字。
html
<div :class="showTotal ? 'total-introduce' : 'detailed-introduce'">
<div class="intro-content" :title="introduce" ref="desc">
<span class="merchant-desc" v-if="introduce">{{introduce}}</span>
<div class="unfold" @click="showTotalIntro" v-if="showExchangeButton">
<p>{{exchangeButton ? '展开' : '收起'}}</p>
</div>
</div>
</div>
css
.total-introduce{
height: auto;
overflow: hidden;
font-size: 26px;
color: #666;
margin-top: 30px;
.intro-content{
.merchant-desc{
width: 100%;
line-height: 40px;
}
}
.unfold{
display: block;
float: right;
width: 80px;
height: 40px;
z-index: 8;
text-align: center;
p{
margin: 0;
line-height: 40px;
color: #0098ff;
}
}
}
.detailed-introduce{
font-size: 26px;
color: #666;
position: relative;
overflow: hidden;
margin-top: 30px;
.intro-content{
//最大高度设为3倍的行间距
max-height: 120px;
line-height: 40px;
word-wrap: break-word;
word-break: break-all;
background-color: #fff;
color: #fff;
overflow: hidden;
.merchant-desc{
width: 100%;
line-height: 40px;
}
&::after,
&::before{
content: attr(title);
position: absolute;
left: 0;
top: 0;
width: 100%;
color: #666;
}
&::before{
display: block;
overflow: hidden;
z-index: 1;
max-height: 80px;
background: #FFF;
}
&::after{
display: -webkit-box;
-webkit-box-orient: vertical;
height: 120px;
// 截取行数
-webkit-line-clamp: 3;
text-overflow: ellipsis;
box-sizing: border-box;
// 行首缩进字符数,值为[(截取行数-1)*尾部留空字符数]
text-indent: -6em;
// 尾部留空字符数
padding-right: 3em;
}
.unfold {
z-index: 8;
width: 80px;
height: 40px;
outline: 0;
position: absolute;
right: 0;
bottom: 0;
text-align: center;
p {
margin: 0;
color: #0098ff;
}
}
}
}
js
export default {
data() {
return {
introduce = ''; // 简介
showTotal = true; // 简介全部显示
exchangeButton = true; // 展开/收起文字改变
showExchangeButton = false; // 是否显示 展开/收起 文字
}
},
methods: {
showTotalIntro() {
this.showTotal = !this.showTotal;
this.exchangeButton = !this.exchangeButton;
}
},
watch: {
introduce: function(){
this.$nextTick(() => {
if (!this.$refs.desc) {
return;
}
const descHeight = window.getComputedStyle(this.$refs.desc).height.replace('px', '');
if (parseInt(descHeight) * 2 > 120) {
this.showExchangeButton = true;
this.exchangeButton = true;
this.showTotal = false;
} else {
this.showExchangeButton = false;
this.showTotal = true;
}
});
}
}