dataTransfer.getData('text')返回undefined

时间:2014-02-17 14:39:26

标签: javascript html5 drag-and-drop

我正在尝试按照http://www.html5rocks.com/en/tutorials/dnd/basics/#toc-dataTransfer

上的html5拖放教程

html是:

 <div id="words">
    <p class="word" draggable="true">word1</p>
    <p class="word" draggable="true">word2</p>
    <p class="word" draggable="true">word3</p>
 </div>

js是:

var dragSrcEl = null;  
function handleDragStart(e) {
this.style.opacity = '0.4'; // this / e.target is the source node.
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.inneHTML); 
}

function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}

e.dataTransfer.dropEffect = 'move'; 

return false;
}

function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}

function handleDragLeave(e) {
this.classList.remove('over'); // this / e.target is previous target element.
}

function handleDrop(e) {
// this / e.target is current target element.

if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (dragSrcEl != this) {
// Set the source column's HTML to the HTML of the column we dropped on.
dragSrcEl.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData('text/html');
//this.innerHTML = temp;
}
return false;
}

function handleDragEnd(e) {
// this/e.target is the source node.

[].forEach.call(words, function (word) {
word.classList.remove('over');
});
}


var words = document.querySelectorAll('#words .word');
[].forEach.call(words, function(word) {
    word.addEventListener('dragstart', handleDragStart, false);
    word.addEventListener('dragenter', handleDragEnter, false);
    word.addEventListener('dragover', handleDragOver, false);
    word.addEventListener('dragleave', handleDragLeave, false);
    word.addEventListener('drop', handleDrop, false);
    word.addEventListener('dragend', handleDragEnd, false);
});

css是:

    .word{
float:left;
margin-right:5px;
cursor:move;
}
.word.over{
color: #ff0000;
}

但是,在所有浏览器或jsfiddle中测试代码时,目标字会改变,但原始字会更改为“undefined” 我在想它是因为

dragSrcEl.innerHTML = this.innerHTML;

正在运作但

this.innerHTML = e.dataTransfer.getData('text/html');

返回undefined,jsfiddle中的测试证实了这一点。

为什么

e.dataTransfer.getData('text/html');

返回undefined?

其值应设置为

e.dataTransfer.setData('text/html', this.inneHTML); 

不是吗?

2 个答案:

答案 0 :(得分:0)

只需将替换部件更改为此

即可
var temp = this.innerHTML;
this.innerHTML = dragSrcEl.innerHTML;
dragSrcEl.innerHTML = temp;

演示:http://jsfiddle.net/fWq4T/

答案 1 :(得分:-1)

更改第5行

 e.dataTransfer.setData('text/html', this.inneHTML);

 e.dataTransfer.setData('text/html', this.innerHTML);

希望这个帮助