<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
function getByClass(clsName,parent){
var oParent=parent?document.getElementById(parent):document,
eles=[],
elements=oParent.getElementsByTagName("*");
for(var i=0;i<elements.length;i++){
if(elements[i].className==clsName){
eles.push(elements[i]);
}
}
return eles;
}
window.onload=drag;
function drag(){
var oTitle=getByClass("mainTop","mainbody")[0];
oTitle.onmousedown=fnDown(event);
}
function fnDown(event){
event=event || window.event;
var oDrag=document.getElementById("mainbody"),
disX=event.clientX-oDrag.offsetLeft,
disY=event.clientY-oDrag.offsetTop;
document.onmousemove=function(event){
event=event || window.event;
fnMove(event,disX,disY)
}
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
}
}
function fnMove(e,posX,posY){
var oDrag=document.getElementById("mainbody"),
l=e.clientX-posX,
r=e.clientY-posY,
winW=document.documentElement.clientWidth || document.body.clientWidth,
winH=document.documentElement.clientHeight || document.body.clientHeight,
maxW=winW-oDrag.offsetWidth,
maxH=winH-oDrag.offsetHeight;
if(l<0){
l=0;
}else if(l>maxW){
l=maxW;
}
if(r<0){
r=0;
}else if(r>maxH){
r=maxH;
}
oDrag.style.left=l+"px";
oDrag.style.top=r+"px";
}
</script>
<style>
body{margin:0;padding:0;}
.mainBody{width:300px;height:300px;background:#3CC;position:absolute;left:450px;top:200px;}
.mainTop{width:100px;height:50px;background:#F66;text-align:center;font-family:"宋体";font-size:24px;margin:0 auto;display:block;}
</style>
</head>
<body>
<div class="mainBody" id="mainbody">
<input type="button" value="拖曳区" class="mainTop" />
</div>
</body>
</html>