使用flex包装在flex容器中的斑马线行:包装

zebra striping rows in a flex container with flex-wrap:wrap

本文关键字:flex 包装 斑马线 使用      更新时间:2023-09-26

假设我使用的是带有flex-direction:rowflex-wrap:wrap的flexbox容器。

根据浏览器窗口的大小,每行中可能有2、3、4个或更多项目。

我想在每隔一行的项目中放置一个灰色背景,模仿表格布局。有简单的方法吗?

小提琴示例:https://jsfiddle.net/mqf7nouc/1/

HTML:

<div class="container">
  <div class="item">
    item 1
  </div>
  <div class="item">
    item 2
  </div>
  <div class="item">
    item 3
  </div>
  <div class="item">
    item 4
  </div>
  <div class="item">
    item 5
  </div>
  <div class="item">
    item 6
  </div>
  <div class="item">
    item 7
  </div>
</div>

CSS:

.container {
  display:flex;
  flex-direction:row;
  flex-wrap:wrap;
}
.item {
  height:50px;
  width:100px;
  text-align:center;
  vertical-align:middle;
  line-height:50px;
  border:1px solid black;
  margin:5px;
}

好吧,这实际上是一项相当困难的任务。我能想到的最好的方法是使用javascript,通过循环并比较项目的高度来找出包装发生的位置。目前,它是一个自执行函数,只会在窗口加载时运行。如果你想让它在加载后有人更改浏览器大小时做出响应,那么把它放在函数中,并在窗口调整时调用该函数

否则,一切都在这里。

(function() {
    var x = 0;
    var counter = 0;
    var boxesPerRow = 0;
    var elements = document.getElementsByClassName("item");
    var totalBoxes = elements.length;
        // Loop to find out how many boxes per row
        for (var i = 0; i < totalBoxes-2; i++){
            x = i+1;
            var temp = elements[i].getBoundingClientRect();
            if (x <= elements.length)
            {
                var next = elements[x].getBoundingClientRect();
                    // Compare height of current vs the next box
                    if (next.top > temp.top && counter ==0)
                    {
                        boxesPerRow = x;
                        counter = 1;
                    }
            }   
        }

        // var marker is where we are applying style
        // var countUpTo is the last box in the row we are styling
        const boxes = boxesPerRow;
        var countUpTo = boxesPerRow;
        var counter = 0;
        // Loop through and apply color to boxes.
        for(var marker = 0; marker < totalBoxes; marker++)
        {   
            if(marker < countUpTo)
            {
                elements[marker].style.backgroundColor = "red";
            }
            else
            {
                counter++;
                if(counter === 1)
                {
                    countUpTo = boxes*(counter+2);
                }
                else{
                    countUpTo = countUpTo + (boxes*2);
                }
                marker = marker+boxes-1;
                // Handles buttom row not being a full set of boxes.
                if(marker> totalBoxes && !(marker > totalBoxes-(boxes*2)))
                {
                    var leftOver = marker-totalBoxes;
                    for(var c = 1; c <= leftOver; c++)
                    {
                        elements[(totalBoxes-c)].style.backgroundColor = "red";
                    }
                }
            }
        }
    })();