日期:2014-05-19  浏览次数:20771 次

求一个拖动层的例子
不要太复杂,越简单越好

要求如下
<div   id= "father ">
<div   id= "child1 "> </div>       //该层可以响应拖动事件并拖动整个father层
<div   id= "child2 "> </div>       //该层需要被带动一起拖动
</div>
实际就是要一个层窗口,
标题区域和内容区域,鼠标在内容区域不可以拖动,鼠标在标题区域可以拖动整个窗口,其中father代表了整个窗口,child1代表了标题区域,child2表示内容区域,


!在此基础上改就行

<script   language= "javascript ">  
var   mouse_x,obj_x,mouse_y,obj_y
var   obj_moveable=false;  

//开始拖动层
function   startDrag(obj){  
mouse_x   =   event.clientX;
mouse_y   =   event.clientY;
obj_x=parseInt(obj.style.left);
obj_y=parseInt(obj.style.top);
obj.setCapture();  
obj_moveable=true;  
}  

//拖动
function   drag(obj)   {  
if(obj_moveable   &&   event.button==1)   {  
obj.style.pixelLeft   =obj_x+(event.clientX-mouse_x)   ;
obj.style.pixelTop   =obj_y+(event.clientY-mouse_y)   ;
}  
}  

//停止拖动
function   stopDrag(obj){  
obj.releaseCapture();  
obj_moveable=false;  
}  
</script>

<div   id= "father "  
onmousedown= "startDrag(this) "  
onmouseup= "stopDrag(this) "  
onmousemove= "drag(this) "   >
<div> 标题,鼠标在此可以拖动整个窗口 </div>
<div> 内容 </div>
</div>

------解决方案--------------------
提供一个参考例子(将以下代码存成HTML看):

<html>
<head>
<title> DRAG the DIV </title>
<style>
*{font-size:12px}
.dragTable{
font-size:12px;
border-top:1px solid #3366cc;
margin-bottom: 10px;
width:100%;
background-color:#FFFFFF;
}
.dragTR{
cursor:move;
color:#7787cc;
background-color:#e5eef9;
}
td{vertical-align:top;}
#parentTable{
border-collapse:collapse;
letter-spacing:25px;
}
</style>
<script defer>

var draged=false;
tdiv=null;
function dragStart(){
ao=event.srcElement;
if((ao.tagName== "TD ")||(ao.tagName== "TR "))ao=ao.offsetParent;
else return;
draged=true;
tdiv=document.createElement( "div ");
tdiv.innerHTML=ao.outerHTML;
tdiv.style.display= "block ";
tdiv.style.position= "absolute ";
tdiv.style.filter= "alpha(opacity=70) ";
tdiv.style.cursor= "move ";
tdiv.style.width=ao.offsetWidth;
tdiv.style.height=ao.offsetHeight;
tdiv.style.top=getInfo(ao).top;
tdiv.style.left=getInfo(ao).left;
document.body.appendChild(tdiv);
lastX=event.clientX;
lastY=event.clientY;
lastLeft=tdiv.style.left;
lastTop=tdiv.style.top;
try{
ao.dragDrop();
}catch(e){}
}
function draging(){//重要:判断MOUSE的位置
if(!draged)return;
var tX=event.clientX;
var tY=event.clientY;
tdiv.style.left=parseInt(lastLeft)+tX-lastX;
tdiv.style.top=parseInt(lastTop)+tY-lastY;
for(var i=0;i <parentTable.cells.length;i++){
var parentCell=getInfo(parentTable.cells[i]);
if(tX> =parentCell.left&&tX <=parentCell.right&&tY> =parentCell.top&&tY <=parentCell.bottom){
var subTables=parentTable.cell