是否可以在 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);
}
});
现在,我的代码实际上比这更复杂,但它提供了我正在做的事情的外壳。
jQuery 工作正常,但是我如何包含动画?
PS:试图让 jsFiddle 运行,但他们的服务器可能已关闭 atm??!!?
最佳答案
首先尝试对其进行动画处理,进行视觉交换,然后在 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;
});
}
});
关于jquery - 在 DOM 上可视化地交换两个 HTML 元素,然后将其全部动画化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19155939/