vue实现超过两行显示展开收起
基于vue-cli2,sass,vant(ui组件):https://youzan.github.io/vant/#/zh-CN/home
具体代码如下:
<template>
<div>
<div class="group">
<div class="text more" ref="more">
占位
</div>
<div class="list" v-for="(item, index) in historyList" :key="index">
<van-row>
<van-col span="12">{{ item.version }}</van-col>
<van-col class="t_right l_text" span="12">{{ item.time }}</van-col>
</van-row>
<div class="l_title">{{ item.title }}</div>
<div
class="text"
ref="textContainer"
:class="{ retract: item.status }"
:style="{ 'max-height': item.status ? textHeight : '' }"
>
{{ item.content }}
</div>
<span
v-if="item.status !== null"
class="link"
@click="more(index)"
>{{ item.status ? "展开" : "收起" }}</span
>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
textHeight: '',
historyList: [
{
version: '7.1.4',
title: '本次更新',
content:
'-听模块新增“文章难度分析”功能~,为你分析文章中词汇、语速等难度,推荐;-听模块新增“文章难度分析”功能~,为你分析文章中词汇、语速等难度,推荐',
time: '2周前'
},
{
version: '7.1.4',
title: '本次更新',
content:
'-听模块新增“文章难度分析”功能~,为你分析文章中词汇、语速等难度,推荐',
time: '5周前'
},
{
version: '7.1.4',
title: '本次更新',
content:
'-听模块新增“文章难度分析”功能~,为你分析文章中词汇、语速等难度,推荐;-听模块新增“文章难度分析”功能~,为你分析文章中词汇、语速等难度,推荐',
time: '6周前'
},
{
version: '7.1.4',
title: '本次更新',
content:
'-听模块新增“文章难度分析”功能~,为你分析文章中词汇、语速等难度,推荐',
time: '9周前'
}
]
}
},
mounted () {
this.historyList.forEach((ele, index) => {
this.$set(
this.historyList,
index,
Object.assign({}, ele, { status: null })
)
})
// DOM 加载完执行
this.$nextTick(() => {
this.calculateText()
//console.log(this.historyList)
})
window.onresize = () => {
this.historyList.forEach((ele, index) => {
this.$set(
this.historyList,
index,
Object.assign({}, ele, { status: null })
)
})
setTimeout(() => {
this.calculateText()
}, 0)
}
},
methods: {
// 计算文字 显示展开 收起
calculateText () {
// 获取一行文字的height 计算当前文字比较列表文字
let oneHeight = this.$refs.more.scrollHeight
let twoHeight = oneHeight * 2 || 40
this.textHeight = `${twoHeight}px`
let txtDom = this.$refs.textContainer
for (let i = 0; i < txtDom.length; i++) {
let curHeight = txtDom[i].offsetHeight
if (curHeight > twoHeight) {
this.$set(
this.historyList,
i,
Object.assign({}, this.historyList[i], { status: true })
)
} else {
this.$set(
this.historyList,
i,
Object.assign({}, this.historyList[i], { status: null })
)
}
}
},
more (index) {
this.historyList[index].status = !this.historyList[index].status
}
}
}
</script>
<style lang="scss" scoped>
.group {
.list {
padding: 5px 0;
border-bottom: 1px solid #eaeaea;
}
.text {
position: relative;
color: #000;
font-size: 14px;
}
.more {
visibility: hidden;
}
.link {
font-size: 12px;
color: #2d95fe;
}
.retract {
position: relative;
overflow: hidden;
}
.retract:after {
content: "...";
position: absolute;
bottom: 0;
right: 2px;
width: 25px;
padding-left: 25px;
background: linear-gradient(to right, transparent, #fff 45%);
}
}
</style>