试图在
HTML5中做一个简单的拖放示例 – 但是当我将图像放入div元素时,我得到以下错误.
Uncaught TypeError: Cannot set property ‘innerHTML’ of null
所以我假设错误消息意味着dragElement为null.我不明白为什么,因为我在dragstart事件中将它设置为img元素的HTML.
有谁知道如何使这项工作?
var dragElement = null; $('#x').bind('dragstart',function (e) { dragElement = this; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/html',this.innerHTML); }); $('#drop-Box').bind('dragover',function (e) { e.preventDefault(); return false; }); $('#drop-Box').bind('drop',function (e) { e.preventDefault(); if (e.stopPropagation) { e.stopPropagation(); } if (dragElement != this) { dragElement.innerHTML = this.innerHTML; this.innerHTML = e.originalEvent.dataTransfer.getData('text/html'); } return false; });
解决方法
dataTransfer是原始事件对象的一部分,而不是jQuery的一部分.请改用e.originalEvent:
http://jsfiddle.net/KWut6/.
e.originalEvent.dataTransfer ...
HTML
<image src="http://lorempixum.com/100/100/" draggable="true" id="x"> <div id="drop-Box">a</div>
JavaScript的
var dragElement = null; $('#x').bind('dragstart',function (e) { dragElement = this; e.originalEvent.dataTransfer.effectAllowed = 'move'; e.originalEvent.dataTransfer.setData('text/html',function (e) { e.preventDefault(); if (e.stopPropagation) { e.stopPropagation(); } if (dragElement != this) { dragElement.innerHTML = this.innerHTML; this.innerHTML = e.originalEvent.dataTransfer.getData('text/html'); } return false; });