How to get the id of the dragged element in javascript?

╄→гoц情女王★ 提交于 2019-12-13 16:41:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!