How to sort DIVs by height?

2019-06-16 19:04发布

I have three divs and I want to sort them by height, from largest to smallest.

<div>smallest</div>
<div>largest</div>
<div>middle</div>

Any idea?

5条回答
来,给爷笑一个
2楼-- · 2019-06-16 19:31

I think http://james.padolsey.com/javascript/sorting-elements-with-jquery/ might provide you a good starting point.

查看更多
一纸荒年 Trace。
3楼-- · 2019-06-16 19:35

It's quite simple. Use .sort():

$('div').sort(function (a, b) {
    return $(a).height() > $(b).height() ? 1 : -1;  
}).appendTo('body');

Code: http://jsfiddle.net/fEdFt/2/

查看更多
乱世女痞
4楼-- · 2019-06-16 19:37

I don't recall if jQuery will wrap the regular array object or not, but if not you can use a selector to get the divs and then use Array.sort(sortFunc) to sort them.

var divsToSort = $('div');  // I believe this returns an array object.

function sortByHeight(a, b) {
   return $(a).height() - $(b).height();
}

divsToSort.sort(sortByHeight);
查看更多
对你真心纯属浪费
5楼-- · 2019-06-16 19:46

Since jQuery returns an array, you can use the sort method on array to reorder the elements. Once they are sorted in the proper order, you can then remove them from the DOM and reinsert them in the order desired.

$('div.sortable').sort( function(a,b) {
   return $(b).height() - $(a).height();
}).appendTo('#container');
查看更多
别忘想泡老子
6楼-- · 2019-06-16 19:49
function sortNumber(a, b) {
            return a - b;
        }

        $(function () {
            var divOrder = [];
            $.each($('div'), function () {
                divOrder.push($(this).height());
            });


            var sortedByHeight = divOrder.sort(sortNumber);

            for (i = 0; i < sortedByHeight.length; i++) {
                $('div').eq(i).height(sortedByHeight[i]);
            }

        });

The html for this was:

<div style='border:solid 1px #ccc; width:100px; height:100px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:400px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:200px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:300px; float:left;'></div>
查看更多
登录 后发表回答