Tecvid, так чтоль?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<style>
html, body {
height: 100%;
}
body {
margin: 0; padding: 0;
display: flex;
align-items: center;
justify-content: center;
}
.parent {
width: 80%;
height: 50%;
border: 5px solid #cc620c;
}
.child {
width: 100px;
height: 100px;;
border-radius: 50%;
background: orange;
cursor: pointer;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
<script>
var parent = document.querySelector('.parent'),
child = parent.children[0];
child.onmousedown = function(event) {
var childCoords = getCoords(this),
parentCoords = getCoords(parent),
shiftX = event.pageX - childCoords.left,
shiftY = event.pageY - childCoords.top,
self = this;
this.style.position = 'relative';
document.onmousemove = function(event) {
var left = event.pageX - shiftX - parentCoords.left,
top = event.pageY - shiftY - parentCoords.top,
rightEdge = parent.clientWidth - self.offsetWidth,
bottomEdge = parent.clientHeight - self.offsetHeight;
left < 0 && (left = 0);
left > rightEdge && (left = rightEdge);
top < 0 && (top = 0);
top > bottomEdge && (top = bottomEdge);
self.style.left = left + 'px';
self.style.top = top + 'px';
};
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
};
return false;
};
child.ondragstart = function() {
return false;
};
function getCoords(elem) {
var box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
}
</script>
</body>
</html>