拖放HTML元素

时间:2017-09-21 04:01:21

标签: javascript html5

        
       function dragStart(event){                                    
                    event.dataTransfer.setData("text", event.target.id);                 
                                }
      function dragOver(event){         
           event.preventDefault();
          dragStart(event1);
                  drop(event1);  
      }    
    function drop(event){
        event.preventDefault();
    var data = event.dataTransfer.getData("text");
    event.target.appendChild(document.getElementById(data));
           }
    
 
    
    .allsections section{width:18%;
   border: 1px solid black;  
   display:inline-block; 
   margin:5px;
    text-align: center;
   vertical-align:middle;
   overflow:auto;
    }
.rowodd{background-color:cornflowerblue;
    padding:5px;
}
.rowodd:hover{background-color:lightblue;}
.roweven{background-color:cornsilk;
    padding:5px;
}
.roweven:hover{background-color:burlywood;}    
 
<body>
  <section class="allsections">
  <section draggable="true" ondragstart="dragStart(event)" ondragover="dragOver(event)" ondrop="drop(event)" class="rowodd" id ="s1">first element</section>
  <section draggable="true" ondragstart="dragStart(event)" ondragover="dragOver(event)" ondrop="drop(event)" class="roweven" id ="s2">second element 
</section>
</section>
</body>

如何使用javascript中的拖放功能交换两个HTML元素(div)的位置?我的意思是当第一个div元素被放在第二个元素上时,第二个div元素会自动地到达第一个元素的位置

1 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码。这适用于大多数浏览器。有时歌剧不受支持。

<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {
    width: 350px;
    height: 70px;
    padding: 10px;
    border: 1px solid #aaaaaa;
}
</style>
<script>
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<p>Drag the W3Schools image into the rectangle:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>

点击此链接:https://www.w3schools.com/html/html5_draganddrop.asp