Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

javascript - Drag'n'drop dataTransfer.getData empty

I'm trying to get drag'n'drop to work, but I seem to be completely missing how the getData/setData works.

I'm using this code (http://jsfiddle.net/ASKte/218/)

var el = angular.element(document.getElementById('drag'));
el.attr("draggable", "true");
el.bind("dragstart", function(e) {
    e.dataTransfer.setData('text', 'Where have you gone?!?!')         
});

var target = angular.element(document.getElementById('drop'));
target.bind("dragover", function(e) {
    if (e.preventDefault) {
        e.preventDefault(); // Necessary. Allows us to drop.
    }
    return false;
});

target.bind("dragenter", function(e) {
    console.debug(e.dataTransfer.types);
    console.debug(e.dataTransfer.getData('text'));
});

I'm using AngularJS here because this is a snippet of a much larger piece of code.

For some reason when dragging the top square on the bottom square, the value of getData('text') is always empty, but I have no idea why...

Any ideas?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The data is only available on drop, this is a security feature since a website could grab data when you happen to be dragging something across the webpage.

var el = angular.element(document.getElementById('drag'));
el.attr("draggable", "true");
el.bind("dragstart", function(e) {
    e.dataTransfer.setData('text', 'Where have you gone?!?!')         
});

var target = angular.element(document.getElementById('drop'));
target.bind("dragover", function(e) {
    if (e.preventDefault) {
        e.preventDefault(); // Necessary. Allows us to drop.
    }
    return false;
});

target.bind("drop", function(e) {
    console.debug(e.dataTransfer.types);
    console.debug(e.dataTransfer.getData('text'));
});  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="drag" style="width: 100px; height: 100px; background-color: blue;"></div>

<div id="drop" style="width: 100px; height: 100px; background-color: green;"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...