gpt4 book ai didi

javascript - 如何计算行中的元素并在之后追加 div

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

我正在尝试编写一个函数来计算一行中的元素数。然后,我想在那么多元素之后插入一个 div,以便它在计数的元素下方占据一整行。

到目前为止,这是我的功能。甚至不确定我是否在正确的轨道上......请引用此 CodePen 以获取更多信息:http://codepen.io/Auzy/pen/gmYBJy

var parentSelector = $('.container');
var childSelector = $('.box');

function countFirstRowItems(parentSelector, childSelector){
var count = 0, theTop = undefined;
$(parentSelector + " > " + childSelector).each(function(){
var thisTop = $(this).offset().top;
if(theTop === undefined){
theTop = thisTop;
}
if(thisTop != theTop){
return false;
}
count++;
});
return count;
}

console.log(countFirstRowItems());

最佳答案

function separateRows(parent, children) {
var $elems = $(parent + ">" + children); // get the elements
var top = $elems.first().offset().top; // get the offsetTop of the first
var n = 1; // n will be the number of items in the same row
while(n < $elems.length && $elems.eq(n).offset().top == top) // while there still elements and the current element got the same offsetTop as the first, increment n
n++;
var $div = $("<div class='div'></div>"); // the div that will take a whole row (see CSS)
$div.insertAfter(parent + ">" + children + ":nth-child(" + n + "n)"); // add the div after each n elements
}

separateRows(".container", ".box");
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-around; /* I added this too (not important though) */
background-color: #333;
}

.box, .div {
background-color: #444;
margin: 1em;
height: 50px;
width: 50px;
border-radius: 1em;
}

.div {
background-color: red;
width: 100%; /* to take a whole row */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>

关于javascript - 如何计算行中的元素并在之后追加 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42403374/

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