如何仅在父div内拖动子div

I make a drag div who has to move only inside the parent div...
When a drag div comes out of the parent div, how to make the div move just inside the parent div?

div child should be clickable, so do not put CSS pointer-events: none;!

码:

document.getElementById("parent").addEventListener('mouseup', mouseUpElement, false);
var modalwindoweditdefaultelement = document.getElementById("child");
var elementdragTop;
var elementdragLeft;

function mouseDownElement(e) {
  document.getElementById("parent").addEventListener("mousemove", myFunctionDragElement, true);
  elementdragTop = event.clientX - document.getElementById("child").offsetLeft;
  elementdragLeft = event.clientY - document.getElementById("child").offsetTop;
}

function mouseUpElement() {
  document.getElementById("parent").removeEventListener("mousemove", myFunctionDragElement, true);
}

function myFunctionDragElement(e) {
  var x = event.clientX;;
  var y = event.clientY;
  document.getElementById("child").style.position = "absolute";
  document.getElementById("child").style.left = x - elementdragTop + 'px';
  document.getElementById("child").style.top = y - elementdragLeft + 'px';
}
#parent {
  width: 500px;
  height: 500px;
  background-color: blue;
  position: absolute;
  margin: 100px;
}

#child {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  margin: 0px;
}
<div id="parent">
  <div id="child" onmousedown="mouseDownElement()"></div>
</div>
评论