在视觉上和DOM上交换两个HTML元素,并为它设置动画?

是否有可能在jQuery中交换两个容器的位置 – 在视觉上和在DOM中,还可以为结果设置动画?

我有:

单击该链接将该div的位置与上面的位置交换。 大多数示例使用绝对定位并偏移top属性来实现此目的……但是当用户在其他地方调用函数时,我需要按照屏幕上显示的顺序读取数据。

所以我想出了这个:

 $('#container div').on('click', '.moveUp', function() { divInQuestion = $(this).closest('div').attr('id'); //id of this div if (divInQuestion > '1') { switchWithDiv = divInQuestion - 1; //id of other div firstSelector = $('#chapterset-'+divInQuestion).html(); //save contents of each div. I actually don't secondSelector = $('#chapterset-'+switchWithDiv).html(); //do it this way, I regenerate the content $('#chapterset-'+divInQuestion).html()firstSelector.replaceWith(secondSelector); //replace div with other div $('#chapterset-'+switchWithDiv).html()secondSelector.replaceWith(firstSelector); } }); 

现在,我的代码实际上比这更复杂,但它给出了我正在做的shell。

jQuery工作正常但是,我如何包含动画?

PS:试图让jsFiddle去,但他们的服务器可能会下降atm ?? !!?

首先尝试动画,进行视觉交换,然后在DOM中交换它们:

http://jsfiddle.net/BYossarian/GUsYQ/5/

HTML:

  

CSS:

 #container { width: 200px; border: 1px solid black; position: relative; } #container div { border: 1px solid black; position: relative; } #container a { display: block; } 

JS:

 var animating = false; $('#container').on('click', '.moveUp', function () { if (animating) {return;} var clickedDiv = $(this).closest('div'), prevDiv = clickedDiv.prev(), distance = clickedDiv.outerHeight(); if (prevDiv.length) { animating = true; $.when(clickedDiv.animate({ top: -distance }, 600), prevDiv.animate({ top: distance }, 600)).done(function () { prevDiv.css('top', '0px'); clickedDiv.css('top', '0px'); clickedDiv.insertBefore(prevDiv); animating = false; }); } });