问题
I want to get the id of the dragged element in javascript in the drop event handler.
div with id place5 is draggable with drop location being another div with id dropArea.
In the drop event handler how to get the id of div(place5)?
<html>
<head>
<style>
.mainArea{
width: 500px;
height : 500px;
border-color:red;
border-style:solid;
border-width:5px;
}
</style>
<script>
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?
}
</script>
</head>
<body>
<div id="dropArea" class="mainArea" ondrop="dropEventHandler(event);" ondragover="event.preventDefault();>
</div>
<div id="place5" draggable="true" ondragstart="dragEventHandler(event);">
</div>
</body>
</html>
回答1:
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.
}
来源:https://stackoverflow.com/questions/21950304/how-to-get-the-id-of-the-dragged-element-in-javascript