console
function dragInit(box, id) {
var $box = document.getElementById(box);
var $div = document.getElementById(id);
var style = {
position: "absolute",
top: "0",
left: "0"
}
for (var k in style) {
$div.style[k] = style[k];
}
$div.onmousedown = function(e) {
e = e || window.event;
var x = e.clientX - $div.offsetLeft;
var y = e.clientY - $div.offsetTop;
document.onmousemove = function(e) {
e = e || window.event;
var L = e.clientX - x;
var T = e.clientY - y;
var boxW = $box.offsetWidth;
var boxH = $box.offsetHeight;
var divW = $div.offsetWidth;
var divH = $div.offsetHeight;
if (L < 0) {
L = 0;
}
if (T < 0) {
T = 0;
}
if (L > boxW - divW) {
L = boxW - divW;
}
if (T > boxH - divH) {
T = boxH - divH;
}
$div.style.left = L + "px";
$div.style.top = T + "px";
console.log(L, T);
}
document.onmouseup = function(e) {
document.onmousemove = null;
document.onmouseup = null;
}
}
return $div;
};
window.onload = function (){
dragInit('parent','children')
}
<div id="parent">
<div id="children"></div>
</div>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
#parent {
position: relative;
width: 700px;
height: 470px;
background: gray;
}
#children {
position: absolute;
width: 100px;
height: 100px;
background-color: antiquewhite;
cursor: move;
}