是否可以在jQuery中交换两个容器的位置 - 在视觉上和在DOM中,还可以为结果设置动画?
我有:
<div id="container">
<div id="one"><a class="moveUp">Up</a></div>
<div id="two"><a class="moveUp">Up</a></div>
<div id="three"><a class="moveUp">Up</a></div>
</div>
点击该链接会将该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继续运行,但他们的服务器可能会崩溃???答案 0 :(得分:9)
首先尝试动画,进行视觉交换,然后在DOM之后将它们交换到:
http://jsfiddle.net/BYossarian/GUsYQ/5/
HTML:
<div id="container">
<div id="one"><a class="moveUp">Up 1</a></div>
<div id="two"><a class="moveUp">Up 2</a></div>
<div id="three"><a class="moveUp">Up 3</a></div>
</div>
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;
});
}
});