1. 程式人生 > 程式設計 >JS實現盒子拖拽效果

JS實現盒子拖拽效果

本文例項為大家分享了JS實現盒子拖拽效果的具體程式碼,供大家參考,具體內容如下

效果:

JS實現盒子拖拽效果

html程式碼:

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>拖拽</title>
<body>
  <div class="leftBox"></div>
  <div class="rightBox">
    <!-- 開啟拖拽屬性draggable -->    
    <div class="circle" draggable="true"></div>
  </div>
</body>
 
</html>

css程式碼:

<style>
    .leftBox {
      display: inline-block;
      width: 100px;
      height: 100px;
      border: 1px solid black;
      border-radius: 10px;
      position: relative;
    }
 
    .rightBox {
      display: inline-block;
      width: 100px;
      height: 100px;
      border: 1px solid black;
      border-radius: 10px;
      position: relative;
    }
 
    .circle {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: radial-gradient(25px at center,white,skyblue);
      /* 絕對居中 */
      position: absolute;
      left: 50%;
      margin-left: -25px;
      top: 50%;
      margin-top: -25px;
    }
  </style>

js程式碼:

<script>
  //獲取dom元素,分別是左盒子 圓圈 右盒子
  var leftBox = document.querySelector('.leftBox');
  var circle = document.querySelector('.circle');
  var rightBox = document.querySelector('.rightBox');
  var text = document.querySelector('.text');
 
  //移動circle
  circle.
 
  //開啟左盒子的移入事件
  leftBox.ondragover = function (event) {
    event.preventDefault();
  }
  leftBox.ondrop = function () {
    leftBox.appendChild(circle);
  }
 
  //開啟右盒子的移入事件
  rightBox.ondragover = function (event) {
    event.preventDefault();
  }
  rightBox.ondrop = function () {
    rightBox.appendChild(circle);
  }
 
</script>

JS實現盒子拖拽效果

關於事件的用法,官方用到了object.addEventListener("dragover",myScript)和event.target.id

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。