<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#box{
width: 300px;
height: 300px;
background: pink;
position: absolute;
}
#two{
position: absolute;
z-index: 999;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script type="text/javascript">
box.function(e){
var e = e || event;//获取event对象
var X = e.clientX-box.offsetLeft;//计算鼠标按下的时候盒子的边界左边界距离;
var Y = e.clientY-box.offsetTop;//计算鼠标按下的时候到盒子的边界上边界距离;
document.function(e){
var e = e || event;
var moveX=e.clientX-X;//计算盒子被移动后到浏览器左边界的距离
var moveY=e.clientY-Y;//计算盒子被移动后到浏览器上边界距离
var winX = document.documentElement.clientWidth;//可见窗口的宽
var winY = document.documentElement.clientHeight;//可见窗口的高
var maxW = winX-box.offsetWidth;
var maxH = winY-box.offsetHeight;
if(moveX<0){
moveX=0;
}
if(moveY<0){
moveY=0;
}
if (moveX>maxW){
moveX=maXW
}
if (moveY>maxH){
moveY=maxH
}
box.style.left = moveX+"px"//设置被移动后左边界的距离
box.style.top = moveY+"px"//设置被移动到后边界的距离
}
}
document.function(){
document.null; //清空被移动的函数
}
</script>