问题
I'm trying to mimic the vote-up vote-down system that is on this website. Is there an easy way to move the position of a div in jquery (with animations)?
Say I have the following items:
<div id="items">
<div id="item1">item 1</div>
<div id="item2">item 2</div>
<div id="item3">item 3</div>
</div>
I'd like to be able to call a function which would smoothly move item 3 up one position to:
<div id="items">
<div id="item1">item 1</div>
<div id="item3">item 3</div>
<div id="item2">item 2</div>
</div>
Is there any easy way to do this in jQuery?
回答1:
Something like this perhaps:
$('.move-up').click(function(e){
var $div = $(this).closest('div');
// Does the element have anywhere to move?
if ($div.index() > 0){
$div.fadeOut('slow',function(){
$div.insertBefore($div.prev('div')).fadeIn('slow');
});
}
});
$('.move-down').click(function(e){
var $div = $(this).closest('div');
// Does the element have anywhere to move?
if ($div.index() <= ($div.siblings('div').length - 1)){
$div.fadeOut('slow',function(){
$div.insertAfter($div.next('div')).fadeIn('slow');
});
}
});
Demo
Basically:
- Grab the element you want to move (
$div) - Fade it out (give a nice UI effect with fadeOut())
- Move it either before or after the previous/next item (with insertBefore() or insertAfter())
- re-fade it back in (another UI effect with fadeIn())
回答2:
Yes there is by changing its css styles. Modify its position http://api.jquery.com/position/ also you can try this How to position one element relative to another with jQuery?
来源:https://stackoverflow.com/questions/7719567/re-ordering-div-positions-with-jquery