flex结合order实现从左到右的瀑布流

13 篇文章 0 订阅

flex结合order实现从左到右的瀑布流
这种方式可以做到先从左到右,再从上到下显示
缺点:需要预先设定flex容器的高度,且调整页面大小时会出现一些间距过大的问题
应对:列表改变时,动态计算flex所需高度

缺陷:整体上的每列数量还是按列平均分布的,并未进行填充。

关键代码
vue

//vue代码
 watch: {
    itemList(newVal) {
      // 为瀑布流重新计算布局
      this.$nextTick(() => {
        const items = document.getElementsByClassName('catalog-item')
        let totalHeight = 0
        // 计算每列的高度
        const columnHeights = [0, 0, 0, 0]
        for (let i = 0; i < items.length; i++) {
          totalHeight += items[i].clientHeight
          columnHeights[i % 4] += items[i].clientHeight
        }
        this.panelHeight = totalHeight / 4 + 100
        // document.body.style.setProperty('--waterfallHeight', `${(totalHeight + maxHeight) / 4}px`)
        // 设置最高列为高度
        document.body.style.setProperty('--waterfallHeight', `${Math.max(...columnHeights) + 10}px`)
      })
    }
  },
//css
.catalog-list {
  display:flex;
  // margin:0 auto;
  flex-direction: column;
  flex-wrap: wrap;
  height: var(--waterfallHeight, 5000px);
}
.catalog-item {
  // box-sizing: border-box;
  // break-inside:avoid;
  position: relative;
  width: 300px;
  padding: 20px;
  padding-bottom: 35px;
  counter-increment: item-counter;
  //改变元素排序,使其成为由左至右的瀑布流
  &:nth-child(4n+1){
    order:0;
  }
  &:nth-child(4n+2){
    order:1;
  }
  &:nth-child(4n+3){
    order:2;
  }
  &:nth-child(4n+4){
    order:3;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值