vue 超过规定行折叠收起

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值