如何在jQuery中获取按位置排序的元素列表?

时间:2015-04-30 19:15:41

标签: javascript jquery

In this plunk我有三个(可拖动)div可以放在屏幕上的任何位置。我需要的是在div被拖动之后获得基于其左侧位置的顺序(即最左边的div应该首先出现在列表中)。如何在jQuery中实现这一点?在我的尝试中,我总是得到原始订单。

HTML

<p>Drag around the divs, then <button id="b1">click</button> to obtain the order (based on each left position)</p>


<div id="div1" 
style="width:60px;height:60px;background-color:orange;margin:20px;float:left">1</div>
<div id="div2" 
style="width:60px;height:60px;background-color:yellow;margin:20px;float:left">2</div>
<div id="div3" 
style="width:60px;height:60px;background-color:pink;margin:20px;float:left">3</div>

的Javascript

$('#div1').draggable();
$('#div2').draggable();
$('#div3').draggable();

$('#b1').click(function() {
  var i = 1;
  var divs = $('div');
  divs.each(function () {
        var div = $(this);
        alert(div.text() + ' is number ' + i);
        i++;
    });
});

1 个答案:

答案 0 :(得分:4)

您可以使用jQuery.prototype.offsetArray.prototype.sort方法。以下代码段根据元素的左侧位置对集合进行排序:

$('#b1').click(function() {
    $('div').sort(function(a, b) {
        return $(a).offset().left > $(b).offset().left;
    }).each(function (i) {
        var div = $(this);
        alert(div.text() + ' is number ' + ++i);
    });
});