js实现拖拽

代码:

 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>
30 
31 html
/**
 * Created by plter on 8/12/16.
 */

(function () {

    var rect = document.querySelector("#rect");

    var rectX = 0, rectY = 0, offsetX, offsetY;

    rect.onmousedown = function (event) {
        offsetX = rectX - event.pageX;
        offsetY = rectY - event.pageY;

        document.onmousemove = function (event) {
            rectX = event.pageX + offsetX;
            rectY = event.pageY + offsetY;

            rect.style.left = rectX + "px";
            rect.style.top = rectY + "px";
        };

        document.onmouseup = function (event) {
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }

})();

js

注意两个点:

①:开始拖拽的时候,应判断好拖拽点的位置。

②:不拖拽的时候能够“放下”。

这也挺实用的,如著名的飞机大战。

补充:2016-10-1108:35:16

代码解释

如图,rectX,rectY指的是鼠标的位置,如果不设置offset,鼠标每次的位置会在rect处,这样的效果很不好。

所以应把鼠标位置调整在鼠标落下的地方,即(把rect转换成offset)

也就有了

  

  offset保存的是rect到offset的距离的相反数。

  

  把rect转换成offset。。

修改:2017-02-15 10:33:23

  上述代码只适合元素位置为left:0;top:0;的时候,

  应该是:

      rectX=rect.offset().left,

      rectY=rect.offset().top;

原文地址:https://www.cnblogs.com/chenluomenggongzi/p/5777580.html