0
我有3个div,我希望他们在将其中一个放在另一个上时切换位置。除了切换之外,一切都很好。当我放下一个div时,它会回到它的默认位置。HTML 5拖放不会丢失
我的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;
}
所以没关系,它只需要删除样式(或在删除时更改它们)。有种尴尬,我看不到它。 : - /好吧,非常感谢。所以让这个问题成为一个例子,说明如何做到这一点。 :) –