大致分为三个步骤:
- 鼠标摁下 onmousedown
- 鼠标移动 onmousemove
- 鼠标抬起 onmouseup
注意的一点是 onmousemove事件和onmouseup事件是在onmousedown事件里面的
代码如下(不支持IE8及以下浏览器):代码一
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
| <!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> body { height: 3000px; } #box1 { width: 100px; height: 100px; background-color: #bbffaa; position: absolute; margin-left: 100px; z-index: 33; } #box2 { width: 100px; height: 100px; background-color: red; position: absolute; top: 300px; left: 300px; } </style> <script> window.onload = function() {
var box1 = document.getElementById("box1"); dary(box1); dary(box2); };
function dary(obj) { obj.onmousedown = function(event) {
event = event || window.event;
var ot = event.pageY - obj.offsetTop + parseInt(getComputedStyle(obj, null)["margin-top"]); var ol = event.pageX - obj.offsetLeft + parseInt(getComputedStyle(obj, null)["margin-left"]);
document.onmousemove = function(event) { event = event || window.event; var top = event.pageY - ot; var left = event.pageX - ol; obj.style.top = top + "px"; obj.style.left = left + "px"; }; document.onmouseup = function() { document.onmousemove = null; document.onmouseup = null;
};
return false; } }; </script> </head>
<body> <p>asdfasd</p> <div id="box1"></div> <div id="box2"></div>
</body>
</html>
|
愿你的坚持终有收获。