如何计算其父元素第一行上的元素数 [英] How to count the number of elements on the first row of their parent element
问题描述
我的问题是,在JavaScript中是否有一种方法可以确定在父元素的第一行中要容纳多少个子元素?然后,我将其乘以固定的行数,然后一次查询那么多行.
My question is, is there a way maybe in JavaScript that I can determine how many child elements are going to fit across the first row of a parent element? I would then multiply that by a fixed number of rows and query up that many at a time.
为了更好地了解发生了什么,如果我查询20个项目,并且页面大小可以容纳每行6个元素,那么我将在最后一行保留两个空格.我想查询的足够多,以便最后一行没有空单元格.
To better understand what is going on, if I query for 20 items and the page size is such that I can fit 6 elements per row, I will be left with two blank spaces on the last row. I would like to query for just enough so that there are no empty cells on the last row.
页面在此处: http://www.spacerock.com/dvds.php
我试图找到一种动态的方式来动态地做到这一点,并根据页面大小对数字进行按摩.
I'm trying to figure out a whiz-bang way to do this dynamically and massage the number by the page size.
推荐答案
好的,我想我现在对您的了解更好.试试这个代码.按原样运行并观察计数,然后进入全屏模式并再次运行.
Ok, I think I understand you better now. Try this code out. Run it as is and observe the count, then go to full-screen mode and run it again.
$(document).ready(function(){
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;
}
$('#btnCount').click(function(){
$('#spnCount').html(
countFirstRowItems('.outer', '.item')
);
});
$('#spnCount').html(
countFirstRowItems('.outer', '.item')
);
});
.outer{
padding:.5em;
margin:.5em;
box-shadow:inset 0px 0px 3px #aaa;
}
.item{
margin:.5em;
height:150px;
width:100px;
border:solid 1px #ddd;
float:left;
background-color:#fdfafa;
}
.clearfix{
clear:both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnCount">Count items on first row</button>
<span id="spnCount">?</span>
<div class='outer'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='clearfix'></div>
</div>
这篇关于如何计算其父元素第一行上的元素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!