gpt4 book ai didi

jquery 选择 float 子项的每个 "row"

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:34 26 4
gpt4 key购买 nike

所以我有多个元素实际上在 flex 父元素中,但看起来它们是 float 的,但它们同时居中(每行最多 3 个子元素)但是当你调整父元素的大小时,它们显然会创建新行。这是我的代码:

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

CSS:

.parent {
width: 100%;
background-color: rgba(0,0,0,0.2);
max-width: 950px;
overflow:auto;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
margin: 0 auto;
}

.child {
width: 300px;
height: 200px;
margin: 8.3px;
background-color: white;
}

或者在我创建的 jsfiddle 中 http://jsfiddle.net/6qdp3sxa/4/ .

我需要在 jquery 中选择每一行。例如当一行中有 3 个 child 时,它可以是这样的:

$('.parent .child').slice(0, 3).each(function() {});
$('.parent .child').slice(4, 7).each(function() {});

但在某种循环中。我不知道该怎么做,你能帮帮我吗?

编辑:这些 child 是动态的,所以我不能自己做这些切片,因为有人可以添加或删除它们。

最佳答案

我想我有一些东西可以确切地知道哪个“行”是一个特定的 div。

如果这不是您要找的东西,这对您来说是一个好的开始。

这个技巧是通过循环 div 并比较它们的顶部偏移来实现的。

console.clear();

var targets = $(".parent .child");

$(window).on("load resize",function(){
// Get the first offset to start a comparison
var divOffset = targets.first().offset().top;

// Loop throught each .child to add a row is not the same offset.
var rows = 0;
var div_per_row = [];
targets.each(function(){
if($(this).offset().top != divOffset){
divOffset = $(this).offset().top;
rows++;
}
div_per_row[rows] = div_per_row[rows]+1 || 1;
});

// Now you have a exact div per row count in an array.
console.log(div_per_row)

// Making fun with it. You could do whatever from this point.
var count = 0;
for(i=0;i<div_per_row.length;i++){
for(k=0;k<div_per_row[i];k++){

var rowNum = i+1;
targets.eq(count).text("I'm on row#"+rowNum);
console.log(i);
count++;
}
}
});
.parent {
width: 100%;
background-color: rgba(0,0,0,0.2);
max-width: 950px;
overflow:auto;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
margin: 0 auto;
}

.child {
width: 300px;
height: 200px;
margin: 8.3px;
background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

由于调整片段的大小并不容易,这里是一个 CodePen .

关于jquery 选择 float 子项的每个 "row",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52066483/

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