一、效果图
二、示例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
.box{
width: 800px;
height: 800px;
background-color: #f5f5f5;
margin: 0 auto;
position: relative;
}
.box .item{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
<div class="item"></div>
</div>
<script type="text/javascript">
var o = document.querySelector(".item"), b = document.querySelector(".box");
o.onmousedown = function(e){
e = e || window.event;
//鼠标相对于盒子的位置
var offsetX = e.clientX - o.offsetLeft;
var offsetY = e.clientY - o.offsetTop;
//鼠标移动
document.onmousemove = function (e) {
e = e || window.event
//判断是否超出
var left = e.clientX - offsetX;
var top = e.clientY - offsetY;
var oWidth = o.offsetWidth, oHeight = o.offsetHeight;
var bWidth = b.offsetWidth, bHeight = b.offsetHeight;
if(left < 0){
left = 0;
}
if(left > bWidth - oWidth){
left = bWidth - oWidth;
}
if(top < 0){
top = 0;
}
if(top > bHeight - oHeight){
top = bHeight - oHeight;
}
o.style.left = left + "px";
o.style.top = top + "px";
}
//鼠标抬起
document.onmouseup = function (e) {
document.onmousemove = null;
document.onmouseup = null;
if (o.releaseCapture) {
o.releaseCapture();//释放全局捕获
}
}
return false;
}
</script>
</body>
</html>