dom元素结构
<ul id="draggable-element" style="list-style: none;padding: 0;margin: 0;">
<li datatype="text" style="width: 100px; height: 100px; background-color: #3498db; cursor: grab;">box1</li>
<li datatype="text" style="width: 100px; height: 100px; background-color: blue; cursor: grab;">box2</li>
</ul>
<ul id="droppable-element" style="list-style: none;padding: 0;margin: 0;width: 200px; height: 200px; background-color: #e74c3c; position: absolute; top: 150px; left: 150px;"></ul>
需要引用的js文件
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
初始化拖拽元素、拖拽目标元素、拖拽目标元素排序
<script>
$(document).ready(function() {
// 初始化排序功能
$('#droppable-element').mouseenter(function() {
$($(this)).sortable({ disabled: false, revert: true });
});
$('#droppable-element').mouseleave(function() {
$($(this)).sortable('destroy');
});
// 选择要拖拽的元素
var $draggable = $("#draggable-element > li");
// 初始化拖拽功能
$draggable.draggable({
cursor: "move",
connectToSortable: "#droppable-element",
helper: "clone",
revert: "invalid"
});
// 选择拖拽目标元素
var $droppable = $("#droppable-element");
// 初始化放置功能
$droppable.droppable({
drop: function(event, ui) {
// 在这里可以处理拖拽成功后的操作
// ui.helper 包含了被拖拽的元素
// 你可以将ui.helper的副本添加到目标元素中
console.log(ui.helper.attr('dataType'), 123);
let element = new String();
if (ui.helper.attr('dataType') === 'text') {
element = `<div>${ui.helper[0].innerText}</div>`
};
$droppable.append(element);
}
});
});
</script>