拖动div简单事例代码

事例文件下载

 1 //拖动容器代码 
 2 var rDrag = {
 3     o: null,
 4     init: function (o) {
 5         o.onmousedown = this.start;
 6     },
 7     start: function (e) {
 8         var o;
 9         e = rDrag.fixEvent(e);
10         e.preventDefault && e.preventDefault();
11         rDrag.o = o = this;
12         o.x = e.clientX - rDrag.o.offsetLeft;
13         o.y = e.clientY - rDrag.o.offsetTop;
14         document.onmousemove = rDrag.move;
15         document.onmouseup = rDrag.end;
16     },
17     move: function (e) {
18         e = rDrag.fixEvent(e);
19         var oLeft, oTop;
20         oLeft = e.clientX - rDrag.o.x;
21         oTop = e.clientY - rDrag.o.y;
22         rDrag.o.style.left = oLeft + 'px';
23         rDrag.o.style.top = oTop + 'px';
24     },
25     end: function (e) {
26         e = rDrag.fixEvent(e);
27         rDrag.o = document.onmousemove = document.onmouseup = null;
28     },
29     fixEvent: function (e) {
30         if (!e) {
31             e = window.event;
32             e.target = e.srcElement;
33             e.layerX = e.offsetX;
34             e.layerY = e.offsetY;
35         }
36         return e;
37     }
38 }
//调用代码
 window.onload=function() {
 var obj = document.getElementById('demo');
        rDrag.init(obj);
 };


html代码
<div id="demo"  style="width: 100px; height: 100px; position: absolute;">拖动我</div>
拖动我
posted @ 2015-10-21 14:30  xingbo  阅读(178)  评论(2编辑  收藏  举报