一個用js實現拖拽的小例子

來源:互聯網
上載者:User

標籤:

代碼:

 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實現拖拽的小例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.