用js怎么实现方块的拖拽移动

用js实现在网页中拖动方块移动的效果

首先我们应在网页中定义一个方块 利用functio (event){   }函数和鼠标事件的onmousedown来对方块的上左边距进行改变来实现方块移动


 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 8     <title>Document</title>
 9     <style>
10         body {
11             margin: 0;
12         }
13 
14         #div1 {
15             width: 300px;
16             height: 300px;
17             background: red;
18             position: absolute;
19             left: 0;
20             top: 0;
21         }
22     </style>
23 </head>
24 
25 <body>
26     <div id="div1"></div>
27 </body>
28 
29 </html>
30 <script>
31     var div1 = document.getElementById('div1')
32     div1.onmousedown = function (event) {
33         var chaX = event.clientX - div1.offsetLeft
34         var chaY = event.clientY - div1.offsetTop
35 
36         document.onmousemove = function (event) {
37             div1.style.left = event.clientX - chaX + 'px'
38             div1.style.top = event.clientY - chaY + 'px'
39         }
40 
41         document.onmouseup = function () {
42             document.onmousemove = null
43         }
44     }
45 
46 
47 </script>

 

posted @ 2021-11-29 10:27  Adinsclay  阅读(377)  评论(0)    收藏  举报