Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

html - Re-ordering div positions with jQuery?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. Grab the element you want to move ($div)
  2. Fade it out (give a nice UI effect with fadeOut())
  3. Move it either before or after the previous/next item (with insertBefore() or insertAfter())
  4. re-fade it back in (another UI effect with fadeIn())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...