flex實現瀑布流布局並實現從左到右排序(order)


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;
  }
}

效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM