思路:
主要是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;
}
});
}
}