最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

drag - How to get the id of a dragged element in JavaScript - Stack Overflow

programmeradmin6浏览0评论

I want to get the id of a dragged element in JavaScript in the drop event handler.

The green div with the id of place5 is draggable and the drop location is another div with the id of dropArea (with a red border).

How do I get the id of the place5 div in the drop event handler?

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?
}
.mainArea {
  width: 200px;
  height: 100px;
  border-color: red;
  border-style: solid;
  border-width: 5px;
}

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

I want to get the id of a dragged element in JavaScript in the drop event handler.

The green div with the id of place5 is draggable and the drop location is another div with the id of dropArea (with a red border).

How do I get the id of the place5 div in the drop event handler?

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?
}
.mainArea {
  width: 200px;
  height: 100px;
  border-color: red;
  border-style: solid;
  border-width: 5px;
}

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

Share Improve this question edited Sep 19, 2022 at 20:54 peejay 1,3553 gold badges12 silver badges21 bronze badges asked Feb 22, 2014 at 5:46 DpkDpk 631 silver badge9 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

Perform the reverse of what you did during the drag start event.

So on dragstart you have:

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

Thus on drop you would have:

function dropEventHandler(theEvent) {
    var id = theEvent.dataTransfer.getData("Text");
    //Other code here.
}
发布评论

评论列表(0)

  1. 暂无评论