gpt4 book ai didi

javascript - 带有 flex-wrap :wrap 的 flex 容器中的斑马条纹行

转载 作者:行者123 更新时间:2023-11-28 01:13:22 29 4
gpt4 key购买 nike

假设我正在使用一个带有 flex-direction:rowflex-wrap:wrap 的 flexbox 容器。

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

我想在每隔一行的元素中放置一个灰色背景,模仿表格布局。有没有简单的方法可以做到这一点?

示例 fiddle 在这里: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;
}

最佳答案

好吧,对于 flex 盒来说,这实际上是一项相当困难的任务。我能想到的最好方法是使用 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";
}
}
}
}

})();

关于javascript - 带有 flex-wrap :wrap 的 flex 容器中的斑马条纹行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36730736/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com