1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <script type="text/javascript"> 8 window.onload=function(event) 9 { 10 /* 11 拖拽box1元素 12 1.当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown 13 2.当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove 14 3.当鼠标松开时,被拖拽元素固定在当前位置 onmouseup 15 */ 16 var box1=document.getElementById("box1"); 17 var box2=document.getElementById("box2"); 18 drag(box1); 19 drag(box2); 20 }; 21 /* 22 获取一个专门用来设置拖拽的函数 23 参数 24 开启拖拽的元素 25 */ 26 function drag(obj){ 27 obj.onmousedown=function(event){ 28 /* 29 设置box1捕获所有鼠标按下的事件(只对IE8及以下有效) 30 设置button对鼠标按下相关的事件进行捕获 31 32 当调用一个元素的setCapture()方法以后,这个元素将会把下一次所有的鼠标按下 33 相关的事件捕获到自身上 34 兼容问题: 35 (1)IE: 有setCapture方法,并且有效果 36 (2)火狐: 有setCapture方法,使用不会报错,但是没效果 37 (3)谷歌: 没有setCapture方法,使用会报错 38 */ 39 if(obj.setCapture) 40 obj.setCapture();//使得选中文字后还能拖拽box1 41 //写法二(更推荐) obj.setCapture&&obj.setCapture(); 42 /* 43 求出偏移量 为了满足o(* ̄︶ ̄*)o鼠标在元素的任意位置可以将其拖拽 44 水平方向 div的偏移量鼠标.client-元素.offsetLeft 45 垂直方向 div的偏移量鼠标.client-元素.offsetTop 46 */ 47 event=event||window.event; 48 var ol=event.clientX-obj.offsetLeft; 49 var ot=event.clientY-obj.offsetTop; 50 document.onmousemove=function(event){ 51 event=event||window.event; 52 var x=event.clientX-ol; 53 var y=event.clientY-ot; 54 obj.style.left=x+"px"; 55 obj.style.top=y+"px"; 56 }; 57 //}; 58 /* 59 当鼠标在box2上,松开鼠标,无法让box1onmouseup 60 原因是此时此刻触发的是box2的onmouseup 61 此处改成document.onmouseup 62 */ 63 document.onmouseup=function(){ 64 //当鼠标松开时,被拖拽元素固定在当前位置onmouseup 65 //取消document的onmousemove事件 66 document.onmousemove=null; 67 //取消document.onmouseup 68 document.onmouseup=null; 69 alert("鼠标松开了_(:з」∠)_"); 70 //当鼠标松开时,取消对事件的捕获 如果不取消,则 71 obj.release&&obj.releaseCapture(); 72 }; 73 /* 74 当我们拖拽一个网页中的内容,浏览器会默认去搜索引擎中??搜索内容, 75 此时会导致拖拽功能异常,这个是浏览器提供的默认行为, 76 如果不希望发生这个行为,则可以通过return false来取消默认行为 77 但是对IE8不起作用 对于IE8,可以采取设置box1捕获所有鼠标按下是事件 78 这样选中全部内容时再拖拽box1时不会使得被选中的文字一起拖拽 79 */ 80 return false; 81 }; 82 } 83 </script> 84 <style type="text/css"> 85 #box1{ 86 width:100px; 87 height:100px; 88 background-color:skyblue; 89 position:absolute; 90 } 91 #box2{ 92 width:100px; 93 height:100px; 94 background-color:yellow; 95 position:absolute; 96 left:200px; 97 top:200px; 98 } 99 </style> 100 <body> 101 可以随意拖拽两个方块_(:з」∠)_ 102 <div id="box1"></div> 103 <div id="box2"></div> 104 </body> 105 </html>
原文:https://www.cnblogs.com/zuiaimiusi/p/11260964.html