//父元素
var boxEl = document.querySelector('.box');
// 子元素
var innerBox = document.querySelector(".innerBox");
innerBox.onmousedown = function() {
//获取各个边距
var startLeft = event.clientX - innerBox.offsetLeft;
var startTop = event.clientY - innerBox.offsetTop;
var boxWidth = boxEl.offsetWidth;
var boxHeight = boxEl.offsetHeight;
var innerWidth = innerBox.offsetWidth;
var innerHeight = innerBox.offsetHeight;
document.onmousemove = function() {
innerBox.style.left = event.clientX - startLeft + 'px'
innerBox.style.top = event.clientY - startTop + 'px'
if (innerBox.offsetTop < 0) {
innerBox.style.top = 0;
}
if (innerBox.offsetLeft < 0) {
innerBox.style.left = 0;
}
if (innerBox.offsetLeft >= boxWidth - innerWidth) {
innerBox.style.left = boxWidth - innerWidth + "px";
}
if (innerBox.offsetTop >= boxHeight - innerHeight) {
innerBox.style.top = boxHeight - innerHeight + "px";
}
}
}
document.onmouseup = function() {
document.onmousemove = null
}
04-30