文章转载自:http://blog.csdn.net/sunxing007/archive/2009/04/22/4100840.aspx,由笑的自然最后编辑
效果预览:
实现源代码:
- <html>
- <head>
- <title>Drag[笑的自然最后修改编辑]</title>
- </head>
- <body>
- <a href="http://blog.csdn.net/xxd851116" mce_href="http://blog.csdn.net/xxd851116">笑的自然最后修改编辑</a>
- <div id="r" style="position:absolute; left:100px; top:100px; background-color:#F00; height:80px; 80px; cursor: pointer;"></div>
- <div id="g" style="position:absolute; left:250px; top:100px; background-color:#0F0; height:80px; 80px; cursor: pointer;"></div>
- <div id="b" style="position:absolute; left:400px; top:100px; background-color:#00F; height:80px; 80px; cursor: pointer;"></div>
- <mce:script type="text/javascript"><!--
- var Drag = {
- //当前被drag的对象
- obj: null,
- //初始化
- init: function(id){
- var o = document.getElementById(id);
- //当onmousedown开始拖拽
- o.onmousedown = Drag.start;
- },
- start: function(e){
- var o = Drag.obj = this;
- //lastMouseX,lastMouseY记录上次鼠标的位置
- o.lastMouseX = Drag.getEvent(e).x;
- o.lastMouseY = Drag.getEvent(e).y;
- //当onmousemove开始移动
- document.onmousemove = Drag.move;
- //当onmouseup终止拖拽
- document.onmouseup = Drag.end;
- },
- move: function(e){
- var o = Drag.obj;
- //dx, dy表示鼠标移动的距离
- var dx = Drag.getEvent(e).x - o.lastMouseX;
- var dy = Drag.getEvent(e).y - o.lastMouseY;
- //因为element.style.left通常返回的结果是'200px'的形式,所以要用parseInt转化
- 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){
- document.onmousemove = null;
- document.onMouseup = null;
- Drag.obj = null;
- },
- //辅助函数,处理IE和FF不同的event模型
- getEvent: function(e){
- if (typeof e == 'undefined'){
- e = window.event;
- }
- //alert(e.x?e.x : e.layerX);
- if(typeof e.x == 'undefined'){
- ee.x = e.layerX;//复制了n遍,到了csdn就变成ee.x了
- }
- if(typeof e.y == 'undefined'){
- ee.y = e.layerY;//复制了n遍,到了csdn就变成ee.x了
- }
- return e;
- }
- };
- //测试代码开始,使三个div具有drag and drop的能力。
- Drag.init('r');
- Drag.init('g');
- Drag.init('b');
- // --></mce:script>
- </body>
- </html>