<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<style type="text/css">
* {
margin:0;
padding:0;
}
.box {
width:100px;
height:100px;
background:red;
position:absolute;
left:0;
top:0;
}
#wrap {
position:relative;
width:500px;
height:500px;
background:#ccc;
margin:50px auto;
}
</style>
</head>
<body>
<div id="wrap">
<div class="box">
</div>
</div>
<script type="text/javascript">
var oBox = document.querySelector(".box");
var owrap = document.querySelector("#wrap");
oBox.onmousedown = function(ev) {
//获取window.event对象兼容写法
var ev = window.event || ev;
//当前鼠标点击位置距离容器的x轴值
var disX = ev.clientX - this.offsetLeft;
//当前鼠标点击位置距离容器的y轴值
var disY = ev.clientY - this.offsetTop;
//鼠标拖动事件
document.onmousemove = function(ev) {
var ev = window.event || ev;
//鼠标拖动容器在wrap容器中的x轴值
var L = ev.clientX - disX;
//鼠标拖动容器在wrap容器中的y轴值
var T = ev.clientY - disY;
//不允许拖动出左边界的判断
if (L < 0) {
L = 0
//不允许拖动出右边界的判断
} else if (L > owrap.offsetWidth - oBox.offsetWidth) {
//若鼠标超出边界值,则将容器固定在边界
L = owrap.offsetWidth - oBox.offsetWidth
}
//不允许拖动出上边界的判断
if (T < 0) {
T = 0
//不允许拖动出下边界的判断
} else if (T > owrap.offsetWidth - oBox.offsetHeight) {
//若鼠标超出边界值,则将容器固定在边界
T = owrap.offsetWidth - oBox.offsetHeight;
}
//赋值移动容器的x轴值
oBox.style.left = L + "px";
//赋值移动容器的y轴值
oBox.style.top = T + "px";
}
//鼠标松开初始化鼠标事件
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
</body>
</html>