下面的极简工作示例将框“一”拖放到框“二”上时交换两个框。问题是,当框“one”被放置时,其样式具有“top”和“left”值,导致其放置在远离应放置位置的位置。它的类包括“ui-draggable-dragging”。顶部和左侧的值似乎与元素在放置之前拖动的量有关。并且拖动被“中断”,因此残留“ui-draggable-dragging”类?
我缺少什么才能使交换顺利进行? full jsfiddle example here
<html>
<head>
<script type="text/javascript" src="includes/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="includes/jquery-ui-1.8.2.custom.min.js"></script>
<script type="text/javascript">
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
$(document).ready(function() {
options = {revert: true};
$("li").draggable(options)
$('#wrapper').droppable({
drop: function(event, ui) {
$(ui.draggable).swapWith($('#two'));
}
});
});
</script>
</head>
<body>
<form>
<ul id="wrapper">
<li id='one'>
<div style="width: 100px; height: 100px; border: 1px solid green">
one<br /></div>
</li>
<li id='two'>
<div style="width: 110px; height: 110px; border: 1px solid red">
two<br /></div>
</li>
</ul>
<br />
</form>
</body>
</html>
最佳答案
这是我的解决方法。
在没有查看和理解 jQuery 内部拖放内容如何工作的情况下,我的猜测是,在拖放中的所有内容完成处理之前需要一段时间。
所以我认为在一切完成之前不应启动交换。因为我不知道这种情况何时发生,所以我在延迟一段时间后进行了交换。我在 drop 事件中使用了 setTimeout 。我必须使用至少 600 毫秒才能确保“一切都清晰且安全”。不到 600 毫秒,“顶部”和“左侧”仍然有一些值,这意味着该过程尚未完成。延迟时间越长,这些值越小;直到任何更大的东西都有顶部并留下相等的零。经过反复试验,600ms 似乎可以做到。
如果有人有“更干净”的解决方案,我将不胜感激。另外,“科学”的解释很有帮助。
关于jquery - 交换两个 jQuery 可拖动列表项无法正常工作(以 jsFiddle 为例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4588229/