How to sort DIVs by height?

安稳与你 提交于 2020-01-03 08:52:45

问题


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>


来源:https://stackoverflow.com/questions/7546164/how-to-sort-divs-by-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!