简体   繁体   English

在HTML5中拖放div

[英]Drag and drop div in HTML5

I try to drag and drop a div element (call it A) in a box B which is a another div. 我尝试将div元素(称为A)拖放到另一个B框B中。 I would like to append an new div A in B each time I drop A in B. 每当我将A放入B中时,我想在B中添加一个新的divA。

Actually I have something like this: 其实我有这样的事情:

function handleDragStart(e) {
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('application/x-moz-node', e.target);
}


function handleDrop(e) {
    //stuff
    this.append(e.dataTransfer.getData('application/x-moz-node'));
    return false;
}

But when I drop A in B: [object HTMLDivElement] is appended in B instead of A. 但是,当我在B中放置A时: [对象HTMLDivElement]附加在B中而不是A中。

Could you tell me where I am wrong and is it the good way to do this? 您能告诉我哪里错了吗,这是个好方法吗?

There are numerous issues with setData and getData and the cross-browser compatibility. setDatagetData以及跨浏览器的兼容性存在许多问题。 You should only rely on the dumb old text/plain 您只应使用哑巴的旧text/plain

I would advise you to just pass the id of the div A and then: 我建议您只传递div A的id ,然后:

function handleDragStart(e) {
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', e.target.id);
}

function handleDrop(e) {
    var a = document.getElementById(e.dataTransfer.getData('text/plain'));
    a = a.cloneNode(true);
    a.id = "a new id here otherwise it is duplicated id";
    this.appendChild(a);

    e.preventDefault();
}

https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode https://developer.mozilla.org/zh-CN/docs/Web/API/Node/cloneNode

Drag and drop is a very common feature. 拖放是非常常见的功能。 It is when you "grab" an object and drag it to a different location. 这是当您“抓取”对象并将其拖到其他位置时。

In HTML5, drag and drop is part of the standard: Any element can be draggable. 在HTML5中,拖放是标准的一部分:任何元素都是可拖动的。 You can refer below link: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop 您可以参考以下链接: http : //www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM