offsetLeft是离其最近的已经定位的元素,如果没有就相对于body元素计算 ,所以要给所折叠的父元素添加相对定位position:relative;
根据子元素offsetLeft值为0的数量来判断是否超过指定行来收起和展开
<template>
<div class="container">
<div style="display: flex;flex-wrap: wrap;position:relative">
<span v-for="item in showData" class="tag">
测试数据({{item})
</span>
</div>
<div v-if="float==1" @click="open()">
展开
</div>
<div v-if="float==2" @click="hide()">
收起
</div>
</div>
</template>
<script>
export default {
data() {
return {
yuanData: [], //存储原数据
showData: [], //存储展示数据
float: null, //是否超过规定行数,1 展开 2 收起
rowIndex: 3, //默认显示几行
splieIndex:0,//截取数组的位置
}
},
created() {
this.getList()
},
methods: {
getList() {
for(let i=1;i<=100;i++){
this.yuanData.push(i)
}
this.showData = this.yuanData
this.$nextTick(() => {
// 获取所有标签节点
let childTags = document.getElementsByClassName('tag')
let total=0 //统计展示行是否超出规定行
//循环所有子标签 判断offsetLeft offsetLeft为0代表一行
for(let i=0;i<this.yuanData.length;i++){
if(childTags[i].offsetLeft==0){
total++
//展示行数超出规定行数,将数组截取到超出第一行的位置
if(total>this.rowIndex){
this.float=1
this.showData=this.yuanData.slice(0,i)
this.splieIndex=i
//结束循环
return
}
}
}
})
},
open(){
this.float=2
this.showData=this.yuanData
},
hide(){
this.float=1;
this.showData=this.yuanData.slice(0,this.splieIndex)
}
}
}
</script>
<style scoped lang="scss">
.container {
span {
padding: 5px 4px;
margin: 0 5px 5px 0;
background-color: aquamarine;
}
}
</style>