您的位置 首页 技术

JS如何实现盒子拖拽效果?(附代码)

JS如何实现盒子拖拽效果?本篇文章给大家详细介绍JS实现盒子拖拽效果的方法,文中示例代码介绍的非常详细。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。 html代…

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>  <p class="leftBox"></p>  <p class="rightBox">    <!-- 开启拖拽属性draggable -->        <p class="circle" draggable="true"></p>  </p></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>

效果:

说明:

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

更多jQuery、Javascript特效,推荐访问:js特效大全!

以上就是JS如何实现盒子拖拽效果?(附代码)的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/79349.html

为您推荐

返回顶部