I need to organize an unknown amount of elements into columns which read vertically. The code below works great for organizing the elements based on a set amount per column, but I won't know the amount of elements so I need to divide all the elements into 4 groups (possibly 5 or 6 cloumns though).
Column 1 = 1st 25% of elements
Column 2 = 2nd 25% of elements
Column 3 = 3rd 25% of elements
Column 4 = 4th 25% of elements
$(window).load(function(){
$('.equalChildHeights').setEqualHeights();
var linkNum = 1;
$('.organizeLinks').each(function(){
if (linkNum <= 10) {
$(this).addClass('linkCol1');
} else if (linkNum > 10 && linkNum <= 20) {
$(this).addClass('linkCol2');
} else if (linkNum > 20 && linkNum <= 30) {
$(this).addClass('linkCol3');
} else if (linkNum > 30 && linkNum <= 40) {
$(this).addClass('linkCol4');
} else if (linkNum > 40 && linkNum <= 50) {
$(this).addClass('linkCol4');
};
linkNum++;
});
$('.linkCol1').each(function(){
$(this).appendTo('.column-1');
});
$('.linkCol2').each(function(){
$(this).appendTo('.column-2');
});
$('.linkCol3').each(function(){
$(this).appendTo('.column-3');
});
$('.linkCol4').each(function(){
$(this).appendTo('.column-4');
});
您正在寻找模数运算符
Here is a working example:
Counts all elements and sets a var with the percentage.
var linkNum = 1;
var totoalLinksCol = $('.organizeLinks').length;
var linksPerCol = Math.ceil(totoalLinksCol/4);
$('.organizeLinks').each(function(){
if (linkNum <= linksPerCol) {
$(this).addClass('linkCol1');
} else if (linkNum > linksPerCol && linkNum <= linksPerCol*2) {
$(this).addClass('linkCol2');
} else if (linkNum > linksPerCol*2 && linkNum <= linksPerCol*3) {
$(this).addClass('linkCol3');
} else if (linkNum > linksPerCol*3 && linkNum <= linksPerCol*4) {
$(this).addClass('linkCol4');
};
linkNum++;
});
$('.linkCol1').each(function(){
$(this).appendTo('.column-1');
});
$('.linkCol2').each(function(){
$(this).appendTo('.column-2');
});
$('.linkCol3').each(function(){
$(this).appendTo('.column-3');
});
$('.linkCol4').each(function(){
$(this).appendTo('.column-4');
});
If you want to divide them into 5 columns, just change the 4 to a 5.
var linksPerCol = Math.ceil(totoalLinksCol/4);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.