我想在dropdown
中创建一个4 columns
菜单(按大陆列出的国家/地区列表)。我正在寻找的是如何确定国家秩序的答案。订单应该是这样的:
示例1:
Column_1 Column_2 Column_3 Column_4
A B C D
示例2:
Column_1 Column_2 Column_3 Column_4
A C D E
B`
示例3:
Column_1 Column_2 Column_3 Column_4
A C E G
B D F
这个想法是平等地使用所有列,但保持每列的顶部到底部的字母顺序。如果可能的话,我正在寻找一个简单的CSS / jQuery解决方案。我怎样才能做到这一点?
答案 0 :(得分:3)
这有点棘手,因为天真的实现倾向于支持早期的列,并且后面的列不足。无论元素数量多少,此版本都会导致四列之间元素的均匀分布。
诀窍是根据剩余的项目数量,在前进到下一列时重新计算每列的项目数。
<ul class='menu'>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<style type='text/css'>
.menu { margin: 0; padding: 0; }
.menu > li {
display: inline-block;
width: 100px;
border: 1px solid red;
padding: 5px;
vertical-align: top;
}
</style>
<script type='text/javascript'>
var data = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
var idx = 0;
// iterate on columns
for (var column = 0; column < 4; ++column) {
// based on remaining items, recalculate per_column
var per_column = Math.ceil((data.length - idx) / (4 - column));
// this_col tracks #items in current column
for (var this_col = 0; this_col < per_column && idx < data.length; ++this_col) {
$('<div></div>').html(data[idx]).appendTo($('.menu li').eq(column));
++idx;
}
}
</script>
答案 1 :(得分:1)
这是一种略有不同的方法,旨在将每一列填满其最大容量。
更新代码示例以使用SELECT DROPDOWNS
HTML:
<div id="container">
<div class="col">
<p>Column 1</p>
<select id="col1"></select>
</div>
<div class="col">
<p>Column 2</p>
<select id="col2"></select>
</div>
<div class="col">
<p>Column 3</p>
<select id="col3"></select>
</div>
<div class="col">
<p>Column 4</p>
<select id="col4"></select>
</div>
</div>
JS:
var list = [1,2,3,4,5,6,7,8,9,10,11,12,13];
var maxCols = 4;
var maxItemsPerColumn = Math.ceil(list.length / maxCols);
var column = 1;
for (var i = 0; i < list.length; i++) {
// For each successive column, we'll want to re-evalutate how many items remain and
// determine how to best distribute them amongst the remaining columns.
var remaining = (list.length - i);
if (remaining % maxItemsPerColumn == 0 && column != 1) {
maxItemsPerColumn = Math.ceil(remaining / (maxCols - column));
}
// Increment column once we've riched the max fill limit.
if ( (i > 0) && !(i % maxItemsPerColumn)) {
column++;
}
var targetId = '#col' + (column);
// With the known column to add to. Use jquery to append option elements to appropriate
// select element.
$(targetId).append('<option value=' + list[i] +'>' + list[i] + '</option>');
}