标签:
代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 7 <style> 8 9 body { 10 margin: 0; 11 } 12 13 #rect { 14 width: 100px; 15 height: 100px; 16 background-color: red; 17 position: fixed; 18 } 19 20 </style> 21 22 </head> 23 <body> 24 25 <div id="rect"></div> 26 27 <script src="main.js"></script> 28 </body> 29 </html>
1 /** 2 * Created by plter on 8/12/16. 3 */ 4 5 (function () { 6 7 var rect = document.querySelector("#rect"); 8 9 var rectX = 0, rectY = 0, offsetX, offsetY; 10 11 rect.onmousedown = function (event) { 12 offsetX = rectX - event.pageX; 13 offsetY = rectY - event.pageY; 14 15 document.onmousemove = function (event) { 16 rectX = event.pageX + offsetX; 17 rectY = event.pageY + offsetY; 18 19 rect.style.left = rectX + "px"; 20 rect.style.top = rectY + "px"; 21 }; 22 23 document.onmouseup = function (event) { 24 document.onmousemove = null; 25 document.onmouseup = null; 26 } 27 } 28 29 })();
注意两个点:
①:开始拖拽的时候,应判断好拖拽点的位置。
②:不拖拽的时候能够“放下”。
这也挺实用的,如著名的飞机大战。
标签:
原文地址:http://www.cnblogs.com/chenluomenggongzi/p/5777580.html