標籤:
代碼:
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>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 })();js
注意兩個點:
①:開始拖拽的時候,應判斷好拖拽點的位置。
②:不拖拽的時候能夠“放下”。
這也挺實用的,如著名的飛機大戰。
一個用js實現拖拽的小例子