How to sort DIVs by height?

2019-06-16 18:52发布

问题:

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?

回答1:

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/



回答2:

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');


回答3:

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



回答4:

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:

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>