这是我的代码:
.item {
display:inline-block;
width:120px;
height:120px;
border:1px solid red;
}

<div id="listing">
<div data-value="5" class="item">item 5</div>
<div data-value="3" class="item">item 3</div>
<div data-value="2" class="item">item 2</div>
<div data-value="1" class="item">item 1</div>
<div data-value="4" class="item">item 4</div>
</div>
&#13;
我想根据div
属性的值对data-value
进行排序,但我想显示使用动画重新排列的项目。我怎么能这样做?
答案 0 :(得分:6)
以下是如何为排序设置动画:
function animateSort(parent, child, sortAttribute) {
var promises = [];
var positions = [];
var originals = $(parent).find(child);
var sorted = originals.toArray().sort(function(a, b) {
return $(a).attr(sortAttribute) > $(b).attr(sortAttribute);
});
originals.each(function() {
//store original positions
positions.push($(this).position());
}).each(function(originalIndex) {
//change items to absolute position
var $this = $(this);
var newIndex = sorted.indexOf(this);
sorted[newIndex] = $this.clone(); //copy the original item before messing with its positioning
$this.css("position", "absolute").css("top", positions[originalIndex].top + "px").css("left", positions[originalIndex].left + "px");
//animate to the new position
var promise = $this.animate({
top: positions[newIndex].top + "px",
left: positions[newIndex].left + "px"
}, 1000);
promises.push(promise);
});
//instead of leaving the items out-of-order and positioned, replace them in sorted order
$.when.apply($, promises).done(function() {
originals.each(function(index) {
$(this).replaceWith(sorted[index]);
});
});
}
$(function() {
$("input").click(function() {
animateSort("#listing", "div", "data-value");
});
});
.item {
display: inline-block;
width: 120px;
height: 120px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Sort" />
<div id="listing">
<div data-value="5" class="item">item 5</div>
<div data-value="3" class="item">item 3</div>
<div data-value="2" class="item">item 2</div>
<div data-value="1" class="item">item 1</div>
<div data-value="4" class="item">item 4</div>
</div>
答案 1 :(得分:1)
虽然您可以在没有jquery的情况下轻松完成此操作,但这是一种(非动画)方式对它们进行排序:
var sorted = $('#listing div').sort(function(a,b) {
return $(a).data('value') - $(b).data('value');
});
$('#listing').html(sorted);
https://jsfiddle.net/yne89aw4/
我会看到我可以做些关于动画排序的方法