【发布时间】:2021-05-14 15:42:48
【问题描述】:
现在我有一个功能性的拖放和复制。我想知道是否有任何方法可以拖动副本,但不能拖放。例如,如果用户按住 shift 键,他/她可以快速单击并放下克隆而不放下拖动的元素。如果通过文档搜索高低并没有找到任何东西。
这是我的代码https://jsfiddle.net/jado66/f8b4ms36/2/:
<!DOCTYPE html>
<html>
<head>
<title>Drag Copy</title>
</head>
<style>
* {user-select: none; }
.cell {width:50px;height:50px;
}
img {width:50px;height:50px;cursor: move;}
table td #dropTable td:hover{background: #dedede;}
#dropTable {
border-spacing: 5px;
border: 1px solid #dedede;
}
.droppable:hover{
transform: scale(1.05);
transition-duration: 0.3s;
}
#dropTable tbody { height:300px; overflow-y:auto; }
</style>
<body>
<!-- Drag Table -->
<table style="border-spacing: 5px;">
<tr>
<td id="image1">
<div class = "cell" ondrop="drop(event)" ondragover="allowDrop(event)">
<img class = "droppable newGate" src="droppable" src="https://picsum.photos/500/500?random=1"
ondragstart="dragStart(event)" id="1" draggable="true"/> </div>
</td>
<td id="image2">
<div class = "cell " ondrop="drop(event)" ondragover="allowDrop(event)">
<img class = "droppable" src="https://picsum.photos/500/500?random=2"
ondragstart="dragStart(event)" id="2" draggable="true" /> </div>
</td>
</tr>
</table>
<hr>
<!-- Drop Table -->
<table>
<tr>
<td>
<table id="dropTable" >
<tr >
<td> <div class = "cell"></div></td>
<td> <div class = "cell" ></div></td>
<td> <div class = "cell" ></div></td>
<td> <div class = "cell" ></div></td>
</tr>
<tr>
<td> <div class = "cell" ></div></td>
<td> <div class = "cell" ></div></td>
<td> <div class = "cell" ></div></td>
<td> <div class = "cell" ></div></td>
</tr>
</tr>
<td> <div class = "cell" ></div></td>
<td> <div class = "cell" ></div></td>
<td> <div class = "cell" ></div></td>
<td> <div class = "cell" ></div></td>
</tr>
</table>
</td>
</tr>
</table>
<script>
const cells = document.querySelectorAll(".cell:empty"); //We only want to add event listeners to empty cells
for (const cell of cells){
cell.addEventListener('dragover',allowDrop);
cell.addEventListener('drop',drop);
}
function dragStart(evt)
{
evt.dataTransfer.setData("Text",evt.target.id);
}
function drop(evt)
{
var data = evt.dataTransfer.getData("Text");
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = Date.now(); /* We cannot use the same ID */
evt.target.appendChild(nodeCopy);
if (evt.shiftKey){
console.log("Shift key pressed. Copy but keep drag");
//Invoke drag command, or prevent drop, etc.
}
}
function allowDrop(ob)
{
ob.preventDefault();
}
</script>
</body>
</html>
【问题讨论】:
-
您的拖放和复制工作正常。那么问题是什么?
标签: javascript html drag-and-drop draggable