我正在建立一個普通的javascript(沒有jQuery)的分類標準管理器,這需要節點(LI元素)的一部分可以被拖拽並變成另一個LI上的子元素。我動態創建了一個「Child」UL,並創建了一個佔位符LI,並將一組嵌套事件偵聽器附加到UL以處理「拖放」部分。可悲的是,「dragover」正常工作,並且正在解僱,但「drop」事件並非如此。我錯過了什麼?嵌套下降不會觸發
我在下面粘貼了我的代碼,但它相當多!我有codepen here的完整源代碼。
TaxonomyManager.prototype.attachDragDropEventListeners = function() {
var manager = this;
[].forEach.call(this._nodes, function(item) {
item.draggable = true;
item.addEventListener('dragstart', dragStartHandler, false);
item.addEventListener('dragover', dragOverHandler, false);
item.addEventListener('dragleave', dragLeaveHandler, false);
item.addEventListener('drop', dropHandler, false);
item.addEventListener('dragend', dragEndHandler, false);
manager._dragSource = null;
function dragStartHandler(e) {
manager._dragSource = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
}
function dragOverHandler(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
removeNewSubTaxonomyPlaceholder();
if ((this.children.length === 0) && (manager._dragSource !== this)) {
var ul = document.createElement('UL');
ul.classList.add('new-sub-taxonomy');
ul.draggable = true;
ul.addEventListener('dragstart', dragStartHandler, false);
ul.addEventListener('dragover', dragOverPlaceholderHandler, false);
ul.addEventListener('dragleave', dragLeaveHandler, false);
ul.addEventListener('drop', dropPlaceholderHandler, false);
ul.addEventListener('dragend', dragEndHandler, false);
var li = document.createElement("LI");
li.classList.add('new-sub-taxonomy-placeholder');
var liText = document.createTextNode("Drop here");
li.appendChild(liText);
ul.appendChild(li);
this.appendChild(ul);
}
e.dataTransfer.dropEffect = 'move';
return false;
}
function dragLeaveHandler(e) {
return false;
}
function dropHandler(e) {
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (manager._dragSource !== this) {
var temp = document.createElement("li");
manager._dragSource.parentNode.insertBefore(temp, manager._dragSource);
this.parentNode.insertBefore(manager._dragSource, this);
temp.parentNode.insertBefore(this, temp);
temp.parentNode.removeChild(temp);
}
return false;
}
function dragEndHandler(e) {
removeNewSubTaxonomyPlaceholder();
return false;
}
function dragOverPlaceholderHandler(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
console.log('this fires');
e.dataTransfer.dropEffect = 'move';
return false;
}
function dropPlaceholderHandler(e) {
console.log('this does not fire');
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
manager.addLeaf(manager._dragSource.firstChild, this.parentNode.parentNode.dataset.id);
manager.renderTree();
return false;
}
function removeNewSubTaxonomyPlaceholder() {
var placeholder = document.querySelector('.new-sub-taxonomy');
if (placeholder) {
placeholder.parentNode.removeChild(placeholder);
}
}
});
};
凌晨3點是代碼的最佳時間! – 2014-10-18 00:35:11