<html>
<head>
<title>PageTitle</title>
<style>...

.drag{...}{
cursor:move;
}



.box{...}{
margin:0px;
width:200px;
border:1pxsolid#ccc;
}
.boxh3.title{...}{
margin:0px;
width:100%;
background-color:#ccc;
}
.boxdiv.content{...}{
margin:0px;
width:100%;
text-align:left;
}
</style>

<scripttype="text/javascript">...
//GreatGhoul
//兼容ff,ie
//要拖动的对象的title设置为'dragable'
//拖动点的class设置为'drag',拖动点必须为可拖动对象的子节点

varDragableObj=...{
handle:null,
dx:0,
dy:0,

init:function(e)...{
e=e||event;
this.handle=e.target||e.srcElement;
if(this.handle.className.indexOf('drag')==-1)return;
while(this.handle.tagName!='HTML'&&this.handle.title!="dragable")...
{
this.handle=this.handle.parentNode||this.handle.parentElement;
}
if(this.handle.title!='dragable')return;
this.handle.style.position='relative';
this.dx=parseInt(this.handle.style.left+0)-e.clientX;
this.dy=parseInt(this.handle.style.top+0)-e.clientY;
document.onmousemove=DragableObj.drag;
},

drag:function(e)...{
e=e||event;

if(this.handle!=null)...{
this.handle.style.left=(e.clientX+this.dx)+'px';
this.handle.style.top=(e.clientY+this.dy)+'px';
}
},

drop:function(e)...{
this.handle=null;
document.onmousemove=null;
}
};
document.onmousedown=DragableObj.init;
document.onmouseup=DragableObj.drop;

document.onselectstart=function(e)...{
e=e||event;
eo=e.target||event.srcElement;
if(eo.className.indexOf('drag')!=-1)returnfalse;
};

</script>
</head>
<body>
<br>例1:
<divclass="box"title="dragable">
<h3class="dragtitle">拖动标题</h3>
<divclass="content">内容</div>
</div>

<br>例2:
<divclass="drag"title="dragable">拖动我</div>

</body>
</html>
this.handle=this.handle.parentNode||this.handle.parentElement;
}
if(this.handle.title!='dragable')return;
this.handle.style.position='relative';
this.dx=parseInt(this.handle.style.left+0)-e.clientX;
this.dy=parseInt(this.handle.style.top+0)-e.clientY;
document.onmousemove=DragableObj.drag;
},
drag:function(e)...{
e=e||event;
if(this.handle!=null)...{
this.handle.style.left=(e.clientX+this.dx)+'px';
this.handle.style.top=(e.clientY+this.dy)+'px';
}
},
drop:function(e)...{
this.handle=null;
document.onmousemove=null;
}
};
document.onmousedown=DragableObj.init;
document.onmouseup=DragableObj.drop;
document.onselectstart=function(e)...{
e=e||event;
eo=e.target||event.srcElement;
if(eo.className.indexOf('drag')!=-1)returnfalse;
};
</script>
</head>
<body>
<br>例1:
<divclass="box"title="dragable">
<h3class="dragtitle">拖动标题</h3>
<divclass="content">内容</div>
</div>
<br>例2:
<divclass="drag"title="dragable">拖动我</div>
</body>
</html>
本文介绍了一种利用HTML、CSS及JavaScript实现网页元素拖拽功能的方法。通过为要拖动的对象设置特定属性,并借助鼠标事件,使得网页中的指定元素可以被用户拖动到页面任意位置。
474

被折叠的 条评论
为什么被折叠?



