jquery - 拖动期间交换元素 - jquery ui
问题描述
我想在拖动期间交换元素。例如,当我将红色盒子拖入带有蓝色盒子的容器中时,该容器中的蓝色盒子会变成红色盒子,而我正在拖动的红色盒子会变成蓝色盒子。那我就继续把蓝框拖走。一切都是拖动过程。
HTML:
<div class="parent">
<div class="child" id="child1"></div>
</div>
<div class="parent">
<div class="child" id="child2"></div>
</div>
<div class="parent">
</div>
JS:
$("document").ready(function() {
$(".child").draggable({
/* revert: true */
});
$(".parent").droppable({
//accept: '.child',
drop: function(event, ui) {
},
over: function(event, ui) {
if ($(this).children().length > 0) {
$(ui.draggable).html($(this).children());
}
$(this).html(ui.draggable);
},
});
});
结果不是我所期望的。你可以在这里看到演示:https ://jsfiddle.net/lion5893/845ybwLs/23/
解决方案
考虑如下函数:
function dragSwap(a, b) {
var id1 = a.attr("id");
var id2 = b.attr("id");
b.attr("id", id1);
a.attr("id", id2);
}
查看您的代码,元素是相同的,两者<div>
,类相同等,唯一的区别是id
.
你可能有这样的事情:
over: function(event, ui) {
if ($(this).children().length > 0 && $(this).children().length == 1) {
var item = $(this).children().eq(0);
var drag = ui.draggable;
dragSwap(item, drag);
}
}
工作示例:https ://jsfiddle.net/Twisty/y285a4bq/
希望有帮助。
推荐阅读
- wordpress - 一种在 WordPress 中创建可重用代码标签的方法
- c++ - gcc >=10.1 和 clang 不检测未使用但设置 lambda
- c# - c# ClientWebSocket 创建多个 websocket 连接
- amazon-web-services - 可以通过将云端域添加到不属于我的域来实现中间人攻击吗?
- javascript - 捕获内容安全策略指令违规
- encryption - 在Android中解密从.net生成的RSA加密值
- swift - 在 Z 和 HStack 中添加 2 个背景?
- bash - 如何检测 .txt 文件中填充行之间的空白行并将其转换为单个选项卡
- python - 如何生成具有“总和”条件的 itertools.product?
- pytorch - 为什么mobilenet比vgg慢?