学习drag and drop

今天读John Resig的Pro Javascript Techniques时候看到他书上给的一个关于drag and drop的例子, 合上书本自己写一个简化版本的。大约20分钟完成, 没有考虑兼容firefox。整个代码封装成一个对象 也是借鉴书中的风格。我觉得很好。Pro Javascript Techniques书中推荐的drag and drop 例子:http://boring.youngpup.net/2001/domdrag

运行代码运行代码

<html> <head> <title>Drag</title> <style type="text/css"> </style> <script type="text/javascript"> var Drag = { //当前被drag的对象 obj: null, //当前所有可脱拽对象中最大的zIndex; maxZIndex: 100, //初始化 init: function(id){ var o = document.getElementById(id); //当onmousedown开始拖拽 o.onmousedown = Drag.start; o.style.zIndex = Drag.maxZIndex; //alert(Drag.maxZIndex); Drag.maxZIndex +=1; }, start: function(e){ var o = Drag.obj = this; //lastMouseX,lastMouseY记录上次鼠标的位置 o.lastMouseX = Drag.getEvent(e).x; o.lastMouseY = Drag.getEvent(e).y; //提高当前被推拽对象的zIndex使之处于最顶层 o.style.zIndex = Drag.maxZIndex; Drag.maxZIndex +=1; //status = o.maxZIndex; //当onmousemove开始移动 document.onmousemove = Drag.move; //当onmouseup终止拖拽 document.onmouseup = Drag.end; }, move: function(e){ //alert(this.maxZIndex); 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'){ e.x = e.layerX;//复制了n遍,到了csdn就变成ee.x了 } if(typeof e.y == 'undefined'){ e.y = e.layerY;//复制了n遍,到了csdn就变成ee.x了 } return e; } }; </script> </head> <body> <div id="r" style="position:absolute; left:100px; top:100px; background-color:red; height:80px; width:80px;"></div> <div id="g" style="position:absolute; left:250px; top:100px; background-color:green; height:80px; width:80px;"></div> <div id="b" style="position:absolute; left:400px; top:100px; background-color:blue; height:80px; width:80px;"></div> </body> <script type="text/javascript"> //测试代码开始,使三个div具有drag and drop的能力。 Drag.init('r'); Drag.init('g'); Drag.init('b'); </script> </html> 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sunxing007

你可能感兴趣的:(JavaScript,html,function,null,div,firefox)