简体   繁体   中英

Appearance of draggable items with HTML5 drag and drop

My code follows:

<style>
   .box {
       border:1px solid black;
       margin:40px;
       padding:20px;
   }
   .dragitem {
       border:1px solid red;
       padding:10px;
       margin:10px;
   }
</style>

<div class="box" ondragover="allowDrop(event)" ondrop="drop(event)">

    <div class="dragitem" draggable="true" ondragstart="drag(event)">one</div>
    <div class="dragitem" draggable="true" ondragstart="drag(event)">two</div>
    <div class="dragitem" draggable="true" ondragstart="drag(event)">three</div>

</div>


<script>
 function drag(e) {
     e.dataTransfer.setData("Text",e.target.id);
 }
 function allowDrop(e) {
     e.preventDefault();
 }
 function drop(e){
     e.preventDefault();
     var data=e.dataTransfer.getData("Text");
     e.target.parentNode.appendChild(document.getElementById(data));
 }
</script>

When I drag one of the draggable divs, that div remains at its position and a semi-transparent clone is being moved. How may I achieve to remain nothing in its original position and when moving around to be visible exactly as it is? In other words, to move the element as it is exactly and without being cloned?

One way to achieve this, would be to listen to the drag event ondrag and animate the element inside the listener to move along with the mouse.

This animation needs to be based on the initial x and y coordinates of the element and the distance and direction it's been dragged.

You have to give an "id" to every element that you want drag/drop.

To give you an example I added the "id", a new div and I deleted the property ".parentNode"

Then you can start to experiment

 <style>
   .box {
       border:1px solid black;
       margin:40px;
       padding:20px;
       height: 200px;
   }
   .dragitem {
       border:1px solid red;
       padding:10px;
       margin:10px;
   }
</style>
<div id="div11" class="box" ondragover="allowDrop(event)" ondrop="drop(event)">

    <div id="div1" class="dragitem" draggable="true" ondragstart="drag(event)">one</div>
    <div id="div2" class="dragitem" draggable="true" ondragstart="drag(event)">two</div>
    <div id="div3" class="dragitem" draggable="true" ondragstart="drag(event)">three</div>

</div>

<div id="div12" class="box" ondragover="allowDrop(event)" ondrop="drop(event)">
</div>

<script>
 function drag(e) {
     e.dataTransfer.setData("Text",e.target.id);
 }
 function allowDrop(e) {
     e.preventDefault();
 }
 function drop(e){
     e.preventDefault();
     var data=e.dataTransfer.getData("Text");
     e.target.appendChild(document.getElementById(data));
 }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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