将图像拖放到div会将其从上一个div

时间:2018-05-22 16:17:49

标签: javascript

我做了这个

https://jsfiddle.net/a4376mr8/

当我将图像div拖放到一个新div时,为什么它不在前一个div中?

const boxes = document.querySelectorAll('.box');
const imageBox = document.querySelector('#draggableItem');
for (const box of boxes) {
    box.addEventListener('dragover', function (e) {
        e.preventDefault();
        this.className += ' onhover';

    })
    box.addEventListener('dragleave', function () {
        this.className = 'box';

    })
    box.addEventListener('drop', function (e) {
        this.className = 'box';
        this.append(imageBox);
    })
}

1 个答案:

答案 0 :(得分:2)

如果我了解您的需求,通过拖放重复图像,则需要克隆div标签dom对象。由于js只是看到它的引用,当你只是追加它时,这会导致它只是从一个地方移动到另一个地方而不是重复。

所以不要只是附加,而是按照以下方式克隆节点(小提琴的第15行)。

this.append(imageBox.cloneNode(true));

见这里:https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

更新了小提琴:https://jsfiddle.net/a4376mr8/1/

相关问题