我正在尝试创建一些可以在 contenteditable div 内拖动的可拖动元素(令牌)。似乎一切正常,除了......在我拖动一个元素并将其放下后,我无法再次拖动它。似乎我无法再次绑定到它的 dragstart 事件。
知道为什么会发生这种情况,我该如何解决?
这是我的小提琴的链接:http: //jsfiddle.net/gXScu/1/
HTML:
<div id="editor" contenteditable="true">
Testime siinkohal seda, et kuidas<br />
on võimalik asja testida.
<span class="draggable" draggable="true" contenteditable="false">Token</span>
</div>
<span class="draggable" draggable="true" contenteditable="false">Token 2</span>
Javascript (jQuery)
var bindDraggables = function() {
console.log('binding draggables', $('.draggable').length);
$('.draggable').off('dragstart').on('dragstart', function(e) {
if (!e.target.id)
e.target.id = (new Date()).getTime();
e.originalEvent.dataTransfer.setData('text/html', e.target.outerHTML);
console.log('started dragging');
$(e.target).addClass('dragged');
}).on('click', function() {
console.log('there was a click');
});
}
$('#editor').on('dragover', function (e) {
e.preventDefault();
return false;
});
$('#editor').on('drop', function(e) {
e.preventDefault();
var e = e.originalEvent;
var content = e.dataTransfer.getData('text/html');
var range = null;
if (document.caretRangeFromPoint) { // Chrome
range = document.caretRangeFromPoint(e.clientX, e.clientY);
}
else if (e.rangeParent) { // Firefox
range = document.createRange();
range.setStart(e.rangeParent, e.rangeOffset);
}
console.log('range', range)
var sel = window.getSelection();
sel.removeAllRanges(); sel.addRange(range);
$('#editor').get(0).focus(); // essential
document.execCommand('insertHTML',false, content);
//$('#editor').append(content);
sel.removeAllRanges();
bindDraggables();
console.log($('[dragged="dragged"]').length);
$('.dragged').remove();
});
bindDraggables();
CSS:
#editor {
border: 2px solid red;
padding: 5px;
}
.draggable {
display: inline-block;
padding: 3px;
background: yellow;
cursor: move !important;
}