解决方案 »

  1.   

    <html>
    <head>
    <meta charset="utf-8">
    <title>self</title>
    <script type="text/javascript" charset="utf-8">
       var Drag = {
       obj:null,
       startX : 0,
       startY : 0,
       init:function(id){
       var o = document.getElementById(id);
       o.onmousedown = Drag.start;
       },
       start : function(e){
       var o = Drag.obj = this;
       o.lastMouseX = Drag.getEvent(e).x;
       o.lastMouseY = Drag.getEvent(e).y;
       Drag.startX = o.style.left;
       Drag.startY = o.style.top;
       document.onmousemove = Drag.move;
       document.onmouseup = Drag.end;
       },
       move : function(e){
       var o = Drag.obj;
       var dx = Drag.getEvent(e).x - o.lastMouseX;
       var dy = Drag.getEvent(e).y - o.lastMouseY;
       var left = parseInt(o.style.left)+dx;
       var top = parseInt(o.style.top)+dy;
       o.style.left = left;
       o.style.top = top;
       o.lastMouseX = Drag.getEvent(e).x;
       o.lastMouseY = Drag.getEvent(e).y;
       },
       end : function(e){
       var o = Drag.obj;
       if(o.style.top != Drag.startY){
       o.style.top = Drag.startY;
       }
       if(o.style.left != Drag.startX){
       o.style.left = Drag.startX;
       }
       document.onMouseup = null;
       document.onmousemove = null;
       document.onmousedown = null;
       Drag.obj = null;
       },
       getEvent : function(e){
       if(typeof e =='undefined'){
       e = window.event;
       }
       if(typeof e.x =='undefined'){
       e.x = e.layerX;
       }
       if(typeof e.y == 'undefined'){
       e.y = e.layerY;
       }
       return e;
       }
       }
    </script>
    </head>
    <body>
    <div id = "r" style="position: absolute;top:100px;left:100px;background-color: red;width: 100px;height: 100px;z-index: 10;"></div>
    <div id = "g" style="position: absolute;top:100px;left:250px;background-color: green;width: 100px;height: 100px;z-index: 10;"></div>
    <div id = "b" style="position: absolute;top:100px;left:400px;background-color: blue;width: 100px;height: 100px;z-index: 10;"></div>
    </body>
    <script type="text/javascript" charset="utf-8">
       Drag.init('g');
       Drag.init('r');
       Drag.init('b');
    </script>
    </html>