效果
鼠标点击文档中任意元素拖拽至任意位置。
思路与流程
1 2 3
| 鼠标按下时,开始拖拽:onmousedown 鼠标移动,元素被拖动:onmousemove 鼠标松开,被拖拽元素固定:onmouseup
|
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #box1{ width: 200px; height: 30px; background-color: bisque; position: absolute; } #box2{ width: 50px; height: 50px; background-color: rgb(184, 127, 59); position: absolute;
left: 200px; top: 200px; } #img1{ width: 250px; position: absolute; } </style> <script> window.onload = function(){ /*流程 * 1.当鼠标按下时,开始拖拽:onmousedown * 2.鼠标移动,元素被拖动:onmousemove * 3.鼠标松开,被拖拽元素固定:onmouseup */ var box1 = document.getElementById('box1'); var box2 = document.getElementById('box2'); var img = document.getElementById('img1'); drag(box1); drag(box2); drag(img);
};
function drag(obj){ obj.onmousedown = function(event){ obj.setPointerCapture; event = event || window.event; var ol = event.clientX - obj.offsetLeft; var ot = event.clientY - obj.offsetTop;
document.onmousemove = function(event){ event = event || window.event; var left = event.clientX - ol; var top = event.clientY - ot; obj.style.left = left+'px'; obj.style.top = top+'px'; obj.innerHTML = 'x='+left+' y='+top; }; document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; obj.releasePointerCapture; }; return false; } }; </script> </head> <body> <div id="box1"></div> <div id="box2"></div> <img src="./img/1.jpg" id="img1"> </body> </html>
|
优化
-
鼠标的偏移量
初始代码的拖拽效果,会出现明显的偏移,即鼠标在移动时,偏离最初点击的位置,用户体验差。
解决方法
元素的偏移量 鼠标.clientX - 元素.offsetLeft
元素的偏移量 鼠标.clientY - 元素.offsetTop
-
拖拽内容时,浏览器会默认去搜索引擎中搜索内容
解决方法1
return false (不兼容ie8及以下)
解决方法2
setCapture()方法 (不支持Chrome)
setPointerCapture属性:鼠标单击时,捕获所有鼠标按下的事件。
releasePointerCapture属性:事件松开时,取消对事件的捕获
-
提取该拖拽函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
function drag(obj){ obj.onmousedown = function(event){ obj.setPointerCapture; event = event || window.event; var ol = event.clientX - obj.offsetLeft; var ot = event.clientY - obj.offsetTop;
document.onmousemove = function(event){ event = event || window.event; var left = event.clientX - ol; var top = event.clientY - ot; obj.style.left = left+'px'; obj.style.top = top+'px'; obj.innerHTML = 'x='+left+' y='+top; }; document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; obj.releasePointerCapture; }; return false; }
|
Tips:
Please indicate the source and original author when reprinting or quoting this article.