其他分享
首页 > 其他分享> > js方块拖拽

js方块拖拽

作者:互联网

拖拽流程:
1、当鼠标在被拖拽元素上按下时,开始摇拽    onm ousedown
2、当鼠标移动时被拖拽元素跟随元素鼠标移动  onm ousemove
3、当鼠标松开时,被拖拽元素固定在当前位置  onm ouseup

mousemove、mouseup是全局有效,使用时用document
mousemove鼠标移动事件后,通过在mouseup里面设置this.onmousemove = null;即可实现触发鼠标抬起事件onmousemove
记得给点击的对象添加样式position:absolute

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         body{
 8             margin: 0;
 9         }
10         #div1{
11             width: 100px;
12             height: 100px;
13             background: red;
14             position: absolute;
15             left: 0;
16             top: 0;
17         }
18         #div2{
19             width: 100px;
20             height: 100px;
21             background: green;
22             position: absolute;
23             left: 500px;
24             top: 200px;
25         }
26 
27     </style>
28 </head>
29 <body>
30  <div id="div1"></div>
31 <div id="div2"></div>
32 </body>
33 </html>
34 <script>
35     var div1=document.getElementById('div1')
36     var div2=document.getElementById('div2')
37     div1.onmousedown=function (event) {
38 
39       var chaX=event.clientX-div1.offsetLeft// 直接获取数字
40       var chaY=event.clientY-div1.offsetTop
41         document.onmousemove=function (event) {
42         div1.style.left=event.clientX-chaX+'px'
43         div1.style.top=event.clientY-chaY+'px'
44         }
45         document.onmouseup=function () {
46     document.onmousemove=null
47 
48         }
49     }
50     if (div1.offsetTop<=div2.offsetWidth+div2.offsetTop){
51         div2.style.background='black'
52     }
53 
54 </script>

 

标签:document,100px,拖拽,onmousemove,方块,js,event,div1
来源: https://www.cnblogs.com/luyanyan/p/15705823.html