<style type="text/css">
* {
margin: 0;
padding: 0;
}
#mbox {
width: 600px;
height: 500px;
margin: 20px auto 0;
background-color: #000;
border: 1px solid burlywood;
position: relative;
}
#xbox {
width: 40px;
height: 40px;
position: absolute;
top: 40px;
left: 40px;
background-color: red;
}
</style>
<body>
<div id="mbox">
<div id="xbox">
</div>
</div>
<script type="text/javascript">
var xbox = document.querySelector("#xbox");
var mbox = document.querySelector("#mbox");
var mstrX = xbox.getBoundingClientRect().left;
var mstrY = xbox.getBoundingClientRect().top;
xbox.onmousedown = function(e) {
//获取事件源,并解决兼容问题。
var ev = e || window.event;
//获取鼠标点击处DIV盒子距离。
var astrX = ev.offsetX;
var astrY = ev.offsetY;
document.onmousemove = function(e) {
var ev = e || window.event;
var lft = ev.clientX - astrX - mstrX;
var tp = ev.clientY - astrY - mstrY;
//禁止移除边框 并实现弹性吸附效果。
//禁止移除横向边框
if(lft < 50) {
lft = 0;
} else if(lft > (mbox.offsetWidth - xbox.offsetWidth)-50) {
lft = mbox.offsetWidth - xbox.offsetWidth;
}
//禁止移除纵向边框
if(tp < 50) {
tp = 0;
} else if(tp > (mbox.offsetHeight - xbox.offsetHeight)-50) {
tp = mbox.offsetHeight - xbox.offsetHeight;
}
xbox.style.left = lft + "px";
xbox.style.top = tp + "px";
// console.log(astrX);
}
//抬起鼠标并清除拖拽。
document.onmouseup = function() {
document.onmousemove = null;
}
//去除冒泡
return false;
};
</script>
</body>
原文地址:https://www.cnblogs.com/xuyx/p/10638481.html