<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0;padding:0;}
#login_box{width:300px;height:150px;background:#eee;
border:1px solid #ccc;position:absolute;left:50%;top:50%;margin-left:-150px;margin-top:-75px;display:block;position: absolute;}
#login_box p{height:20px;border-bottom:1px solid #ccc;font-size:12px;padding:6px 0 0 5px;font-weight:bold;}
#close{width:14px;height:14px;background:yellow no-repeat;position:absolute;right:4px;top:6px;}
</style>
<script>
window.onload=drag;
function drag(){
var ott = getClassName('title','login_box')[0];
ott.onmousedown = ottDown;
}
function ottDown(event){
var dl = document.getElementById('login_box');
//光标按下时距离面板的左、上距离
var jdlx = event.clientX-dl.offsetLeft,
jdly = event.clientY-dl.offsetTop;
//面板中间到边边距离
var mbx = dl.offsetWidth/2,
mby = dl.offsetHeight/2;
//获取窗口最大值
var maxW=document.documentElement.clientWidth - dl.offsetWidth,
maxH=document.documentElement.clientHeight - dl.offsetHeight;
document.onmousemove = function(event){
event = event ||document.event;
if(jdlx>mbx){
var m = jdlx - mbx;
var n = mby - jdly;
var x = event.clientX - m,
y = event.clientY + n;
if(x<0){
x=0;
}else if(x>maxW){
x=maxW;
}
if(y<0){
y=0;
}else if (y>maxH){
y=maxH;
}
dl.style.left = x +'px';
dl.style.top = y +'px';
}else if (jdlx<mbx){
var m = mbx - jdlx;
var n = mby - jdly;
var x = event.clientX + m,
y = event.clientY + n;
if(x<0){
x=0;
}else if(x>maxW){
x=maxW;
}
if(y<0){
y=0;
}else if (y>maxH){
y=maxH;
}
dl.style.left = x +'px';
dl.style.top = y +'px';
}
//求出点击位置距离登录窗口的left、top
// var jdlx = event.clientX-dl.offsetLeft;
// var jdly = event.clientY-dl.offsetTop;
}
}
//封装getClassName方法
function getClassName(classn,parent){
var oParent = parent?document.getElementById(parent):document;
var oc = [];
var otn=oParent.getElementsByTagName('*');
for(i=0,l=otn.length;i<l;i++){
if(otn[i].className==classn){
oc.push(otn[i]);
}
}
return oc;
}
</script>
</head>
<body>
<div id="login_box">
<p class="title">用户登录</p><span id="close"></span>
</div>
</body>
</html>
//在HBuilder里面一开始执行发现光标始终跟着面板中心,所以设置有点不一样。但是边界设置=0之后发现实际边界向左偏移了。
是你容器没有处理好