拖动管理组件
说明:
在作网页时,有时想允许用户拖动一个标签,此时用第三方UI组件库是个不错的注意。如果想自已写如何写呢?自已只想写一次,以后都可用,又如何做呢?
下面中的源代码实现了这个想法。在firefox表现特好,在ie6下可以拖动,google的还没测试。
下面的代码中,FDrag类是核心的代码。对外界来说,仅有一个add方法。如果用户想让哪个标签可以拖动,只需把该标签的id名通过add方法传进去即可。
例:下面id为xxx,yyy的div标签可以拖动。
<<!doctype html public "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="utf-8"><head><title> 拖动对象 Drag Object (兼容:IE、Firefox、 ... )</title><meta http-equiv="content-type" content="text/html; charset=utf-8" /><script language="javascript"> function FDrag(){ this.ie=document.all; this.nn6=document.getElementById&&!document.all; this.isdrag=false; this.x; this.y; this.oDragObj; this.nTX; this.nTY; this.list = new Array(); this.listTarg=new Array(); this.add=function (divID){ this.list.push(divID);//var d=list.pop(); var d=document.getElementById(divID); this.listTarg.push(d); d.style.position="relative"; d.style.cursor="move";d.onmousedown=(function(v) {return function() {v.initDrag(v,arguments[0]);// arguments装着鼠标事件};}) (this);d.onmouseup=(function(v) {return function() {v.isdrag=false;};}) (this);d.onmousemove=(function(v) {return function() {v.moveMouse(v,arguments[0]); //arguments装着鼠标事件};}) (this); } this.moveMouse=function (o,e) { if (o.isdrag) { o.oDragObj.style.top = (o.nn6 ? o.nTY + e.clientY - o.y : o.nTY + event.clientY - o.y)+"px"; o.oDragObj.style.left = (o.nn6 ? o.nTX + e.clientX - o.x : o.nTX + event.clientX - o.x)+"px"; return false; } } this.initDrag=function (o,e) { var oDragHandle =o.nn6 ? e.target : event.srcElement; var isExist=false; for (var i=0 ; i<this.list.length;i++){ if (this.list[i]==oDragHandle.id){ isExist=true; break; } } if(isExist){ o.isdrag = true; o.oDragObj = oDragHandle; o.nTY = parseInt(o.oDragObj.style.top+0); o.y = o.nn6 ? e.clientY : event.clientY; o.nTX = parseInt(o.oDragObj.style.left+0); o.x = o.nn6 ? e.clientX : event.clientX; return false; } } }</script></head><body><div id="xxx" style="border:1px solid #ff6d00;background:#ffd801;width:240px;padding:5px 0;">xxx11 <div id="zzz" style="border:1px solid #ff6d00;background:#ffd801;width:240px;padding:5px 0;">zzz11</div></div><div id="yyy" style="border:1px solid #ff6d00;background:#ffd801;width:240px;padding:5px 0;" >yyy11</div><script language="javascript"> var f=new FDrag (); f.add("xxx"); f.add("yyy");</script></body></html>.dragAble {position:relative;cursor:move;}