如何在一个字段上拖放多个元素

时间:2015-09-01 16:29:23

标签: javascript jquery html

我正在尝试实现一个让我将元素列表拖放到矩阵中的函数。

我现在尝试的第一步是简单地将一个元素拖入一个区域。它在第一个元素上正确,但第二个元素和其他元素都没有。

代码

我有下一个 JavaScript 代码:

var dragSrcEl = null;

function dragStart(event) {
    event.dataTransfer.setData("Text", event.target.id);
}

function dragEnter(event) {
    if ( event.target.className == "droptarget" ) {
        document.getElementById("demo").innerHTML = "Entered the dropzone";
        event.target.style.border = "3px dotted red";
    }
}

function dragLeave(event) {
    if ( event.target.className == "droptarget" ) {
        document.getElementById("demo").innerHTML = "Left the dropzone";
        event.target.style.border = "";
    }
}

function allowDrop(event) {
    event.preventDefault();
}

function drop(event) {
    event.preventDefault();
    var data = event.dataTransfer.getData("Text");
    event.target.appendChild(document.getElementById(data));
}

HTML 通过执行下一个代码来使用它:

...
            <div class="input-group input-group-option col-xs-12" ondragstart="dragStart(event)" draggable="true" id="dragtarget">
              <span class="input-group-addon" id="sizing-addon2">1</span>
              <input type="text" name="option[]" class="form-control" placeholder="Focus me">
              <span class="input-group-addon">
                <span class="glyphicon glyphicon-align-justify"></span>
              </span>
            </div>

            <div class="input-group input-group-option col-xs-12" ondragstart="dragStart(event)" draggable="true" id="dragtarget">
              <span class="input-group-addon" id="sizing-addon2">2</span>
              <input type="text" name="option[]" class="form-control" placeholder="Focus me">
              <span class="input-group-addon">
                <span class="glyphicon glyphicon-align-justify"></span>
              </span>
            </div>

            <div class="input-group input-group-option col-xs-12" ondragstart="dragStart(event)" draggable="true" id="dragtarget">
              <span class="input-group-addon" id="sizing-addon2">3</span>
              <input type="text" name="option[]" class="form-control" placeholder="Focus me">
              <span class="input-group-addon">
                <span class="glyphicon glyphicon-align-justify"></span>
              </span>
            </div>
...

如何拖放多个元素?

JSFiddle

1 个答案:

答案 0 :(得分:1)

请尝试这个:

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    if (ev.target.childNodes.length === 0) {
        ev.target.appendChild(document.getElementById(data));
    }    
}

下面的演示:

DEMO

DEMO 1