【发布时间】:2011-10-18 08:38:18
【问题描述】:
我有一个案例,我获得了一个 UL,以及未知数量的 LI。我希望使用 JS 将 LI 拆分为 2 个 UL(我使用的是 jQuery)。我可以按 LI 的数量平均分割 UL,但我也想根据每个 LI 的高度来分割它,以便两个 UL 接近相同的高度。
对此的任何帮助将不胜感激,我觉得我开始使用的方法没有取得任何进展。
谢谢。
编辑:我目前拥有的 JS 代码。 HTML 只是一个直接的 UL/LI,每个 LI 可以有不同的高度。
var $sections = $('div.subsection');
$sections.each(function(){
var $section = $(this);
var $list = $section.children('ul');
var $items = $list.children('li');
var itemCount = $items.size();
var leftover = itemCount % 2;
var itemsPerColumn = Math.floor(itemCount / 2);
var $newList = $('<ul />');
$items.each(function(){
var $this = $(this);
var index = $items.index($this);
if (index >= (itemsPerColumn + leftover)) {
$this.remove().appendTo($newList);
}
});
$list.after($newList);
_equalizeListHeights();
function _equalizeListHeights(){
var listHeight = $list.height();
var newListHeight = $newList.height();
if (listHeight > newListHeight){
var $lastItem = $list.children('li:last');
var lastItemHeight = $lastItem.height();
if (listHeight - lastItemHeight > newListHeight + lastItemHeight){
$lastItem.remove().prependTo($newList);
_equalizeListHeights();
}
}
}
});
【问题讨论】:
-
请提供 HTML 和 CSS,以便我们查看。 ;-)
-
你的方法是什么??
-
对不起,我附上了相关代码
-
这可能更适合math.stackexchange:给定一组数字(高度),将它们分成两组,最小化|sum(A) - sum(B)|
-
@alex:您可以在 math.stackexchange 上简化您的问题:给定一组整数,找到一个子集,其总和尽可能接近整个集合总数的一半,但不超过所述总数(见我的回答)。
标签: javascript jquery