如何在 JavaScript 中获取拖动元素的 id

Dpk*_*Dpk 4 javascript drag

我想在放置事件处理程序中获取JavaScriptid中拖动元素的。

div带有idof的绿色place5是可拖动的,放置位置是另一个div带有idof 的dropArea(带有红色边框)。

如何获取drop 事件处理id程序place5 div中的 ?

function dragEventHandler(theEvent) {
  theEvent.dataTransfer.setData("Text", theEvent.target.id);
  // some code here.
}

function dropEventHandler(theEvent) {
  // how to get the id of div with id "place5" here?
}
Run Code Online (Sandbox Code Playgroud)
.mainArea {
  width: 200px;
  height: 100px;
  border-color: red;
  border-style: solid;
  border-width: 5px;
}

#place5 {
  background: green;
  height: 20px;
  width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="dropArea" class="mainArea" ondrop="dropEventHandler(event);" ondragover="event.preventDefault();">
</div>
<div id="place5" draggable="true" ondragstart="dragEventHandler(event);">
</div>
Run Code Online (Sandbox Code Playgroud)

小智 5

执行与拖动开始事件期间执行的操作相反的操作。

所以在 Dragstart 上你有:

function dragEventHandler(theEvent) {
    theEvent.dataTransfer.setData("Text", theEvent.target.id);
    //Some code here.
}
Run Code Online (Sandbox Code Playgroud)

因此,在下降时你会得到:

function dropEventHandler(theEvent) {
    var id = theEvent.dataTransfer.getData("Text");
    //Other code here.
}
Run Code Online (Sandbox Code Playgroud)