我想拖动可排序容器的 div 并将它们放到可放置的 div (不可排序)上。我尝试过使用 html5 拖放事件,但没有一个被解雇。 最重要的是,可排序容器上的 Dragstart 事件不会被触发。 有人可以建议我一个解决方案吗?我只想触发 Dragstart 事件。这是我的完整代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Sortable - Handle empty divsts</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<style>
.draggableDivs{
background-color: orange;
border: solid black;
}
</style>
</head>
<body>
<div id="sortable" style="float: left;">
<div class="draggableDivs" draggable="true">Can be dropped !!..</div>
<div class="draggableDivs" draggable="true">..on an empty list</div>
<div class="draggableDivs" draggable="true">Item 3</div>
<div class="draggableDivs" draggable="true">Item 4</div>
<div class="draggableDivs" draggable="true">Item 5</div>
</div>
<div id="dropTarget" style="width: 500px; height: 500px; background-color: skyblue; float: left; text-align: center">
<h4>Drop Here</h4>
</div>
<script>
$("#sortable").sortable();
document.getElementById('sortable').addEventListener('dragstart', function(evt) {
console.log("The 'dragstart' event fired.");
evt.dataTransfer.setData('text', evt.target.textContent);
}, false);
</script>
</body>
</html>
最佳答案
您可以使用 jquery ui 实现如下功能:
基本上,我们克隆被拖动的元素并将其附加到 drop event 上的 droppable 中,因为如果我们删除被拖动的元素,jQuery ui 就会向我们抛出错误。
然后我们删除 stop event 中的实际元素回调。
$("#sortable").sortable();
$("#dropTarget").droppable({
accept: "div",
drop: function(event, ui) {
ui.draggable.clone().appendTo(this);
ui.draggable.remove();
}
})
#sortable {
float: left;
}
.draggableDivs {
background-color: orange;
border: solid black;
}
#dropTarget {
width: 500px;
height: 500px;
float: left;
text-align: center;
background-color: skyblue;
}
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div id="sortable">
<div class="draggableDivs">Can be dropped !!..</div>
<div class="draggableDivs">..on an empty list</div>
<div class="draggableDivs">Item 3</div>
<div class="draggableDivs">Item 4</div>
<div class="draggableDivs">Item 5</div>
</div>
<div id="dropTarget">
<h4>Drop Here</h4>
</div>
旁注:
- 不要将 native 拖放与 jquery ui 混合。
- 不要混合使用内联样式和内部/外部样式。如果可能的话,完全避免使用内联样式。 Why Use CSS?
关于javascript - 如何将可排序的 div 拖到外部元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26671973/