JS:拖放返回错误

时间:2017-01-29 03:36:34

标签: jquery html function events drag-and-drop

我有以下代码,但无法让它工作。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- add jquery -->

<div class="dropzone" style="width: 180px; height: 180px; padding: 10px; margin: 0px; border: 1px solid black;"></div><br>
<div class="dropzone" style="width: 180px; height: 180px; padding: 10px; margin: 0px; border: 1px solid black;">
    <img class="dragable" src="https://image.spreadshirtmedia.net/image-server/v1/compositions/22839312/views/1,width=300,height=300,version=1478003241/smiley-smile-men-s-t-shirt.jpg" width="180">
</div>
<script>
    $(".dropzone").on("dragover", function(ev) {
        ev.preventDefault();
    });

    $(".dropzone").on("drop", function(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    });

    $(".dragable").on("dragstart", function(ev) {
        ev.dataTransfer.setData("text", ev.target.id);
    });
</script>

https://jsfiddle.net/yv6uuzxn/

这是一个简单的拖放功能。当我在ondragstartondrop标记内有ondragoverdivimg但我将其移至脚本时,我会开始错误。 drag and drop.php:14 Uncaught TypeError: Cannot read property 'getData' of undefineddrag and drop.php:19 Uncaught TypeError: Cannot read property 'setData' of undefined。我可能看起来很简单,但我找不到它。

1 个答案:

答案 0 :(得分:1)

我在您的笑脸图片中添加了属性draggable="true"和ID id="myImg" 然后,如果您将dataTransfer事件属性设置并导入originalEvent,则可以正常使用 ;)

$(".dropzone").on("dragover", function(ev) {
  ev.preventDefault();
});

$(".dropzone").on("drop", function(ev) {
  ev.preventDefault();
  var data = ev.originalEvent.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
});

$(".dragable").on("dragstart", function(ev) {
  ev.originalEvent.dataTransfer.setData("text", ev.target.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropzone" style="width: 180px; height: 180px; padding: 10px; margin: 0px; border: 1px solid black;"></div>
<br>
<div class="dropzone" style="width: 180px; height: 180px; padding: 10px; margin: 0px; border: 1px solid black;">
  <img class="dragable" draggable="true" id="myImg" src="https://image.spreadshirtmedia.net/image-server/v1/compositions/22839312/views/1,width=300,height=300,version=1478003241/smiley-smile-men-s-t-shirt.jpg" width="180">
</div>