如何获取JavaScript中被拖动元素的ID? [英] How to get the id of the dragged element in javascript?

查看:175
本文介绍了如何获取JavaScript中被拖动元素的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

div ID为place5的div可与

div with id place5 is draggable with drop location being another div with id dropArea.

在放置事件处理程序中,如何获取div(place5)的ID?

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>


推荐答案

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

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

因此,在dragstart上,您将:

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.
}

这篇关于如何获取JavaScript中被拖动元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆