HTML 5拖放不丢弃

时间:2014-03-29 18:43:17

标签: javascript html5 drag-and-drop

我有3个div,当我将其中一个放在另一个上时,我希望它们切换位置。除了切换之外,一切都还可以。当我放弃div时,它会回到默认位置。

我的HTML& js代码:

<div class="drop" draggable="true" style="background-color: blue;"></div>
<div class="drop" draggable="true" style="background-color: red;"></div>
<div class="drop" draggable="true" style="background-color: green;"></div>


<script>
    var draggedData = null;

    /* start dragging an item */
    function dragStart(ev) {
        this.style.opacity = '0.4';

        draggedData = this;

        ev.dataTransfer.effectAllowed = 'move';
        ev.dataTransfer.setData('text/html', this.innerHTML);
    }

    /* item is moved over the div */
    function dragOver(ev) {
        if (ev.preventDefault)
            ev.preventDefault();    // allows to drop an item

        ev.dataTransfer.dropEffect = 'move';    // item is moved to a new location

        return false;
    }

    /* item enters the div */
    function dragEnter(ev) {
        this.classList.add('dragover');
    }

    /* item leaves the div */
    function dragLeave(ev) {
        this.classList.remove('dragover');
    }

    /* item is dropped on a div */
    function dragDrop(ev) {
        if (ev.stopPropagation)
            ev.stopPropagation();   // stops the browser redirecting

        if(draggedData != this) {
            draggedData.innerHTML = this.innerHTML;
            this.innerHTML = ev.dataTransfer.getData('text/html');
        }

        return false;
    }

    /* after finishing the move (successful or unsuccessful) */
    function dragEnd(ev) {
        [].forEach.call(cols, function (col) {
            col.classList.remove('dragover');
        });
        this.style.opacity = '1';
    }


    var cols = document.querySelectorAll('.drop');
    [].forEach.call(cols, function(col) {
        col.addEventListener('dragstart', dragStart, false);
        col.addEventListener('dragenter', dragEnter, false);
        col.addEventListener('dragover', dragOver, false);
        col.addEventListener('dragleave', dragLeave, false);
        col.addEventListener('drop', dragDrop, false);
        col.addEventListener('dragend', dragEnd, false);
    });
</script>

和我的css:

    .drop {
    width: 200px;
    height: 50px;
    border: 1px solid black;
    background-color: red;
    margin: 10px;
}

.dragover {
    border: 2px dashed black;
}

1 个答案:

答案 0 :(得分:1)

请尝试使用此HTML。 ;)

<div class="drop" draggable="true" style="background-color: blue;">blue</div>
<div class="drop" draggable="true" style="background-color: red;">red</div>
<div class="drop" draggable="true" style="background-color: green;">green</div>

我认为问题是你没有改变内联CSS。