<div class="box" id="box">
  <div id="ccc" class="aaa"></div>
</div>
.box {
  width: 60%;
  height: 60vh;
  margin: 200px auto;
  /*display: flex;*/
  /*justify-content: center;*/
  /*align-items: center;*/
  position: relative;
  border: 2px solid red;
}

.aaa {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: rgb(245, 230, 99);
  border: 10px solid rgba(136, 136, 136, 0.5);
  border-radius: 50%;
}

.aaa:hover {
  cursor: pointer;
  border-width: 20px;
}

.aaa:active {
  background-color: rgba(168, 218, 220, 1);
}
/* mousedown 鼠标进入
 *  mousemove 鼠标移动
 *  mouseup 鼠标离开
 * */
let box = document.querySelector("#box");
let ccc = document.querySelector("#ccc");

ccc.onmousedown = function (event) {
  // 子盒子
  let w = ccc.getBoundingClientRect().width / 2;
  let h = ccc.getBoundingClientRect().height / 2;
  // 大盒子-小盒子
  let width = box.getBoundingClientRect().width - w;
  let height = box.getBoundingClientRect().height - h;
  // 按下的位置距离左侧的差值
  let x = event.clientX - this.offsetLeft;
  let y = event.clientY - this.offsetTop;
  // 移动
  document.onmousemove = function (e) {
    // 移动的坐标-左侧的坐标=子盒子的坐标
    let x1 = e.pageX - x;
    let y1 = e.pageY - y;
    if (-w < x1 && x1 < width) {
      ccc.style.left = x1 + "px";
    }
    if (-h < y1 && y1 < height) {
      ccc.style.top = y1 + "px";
    }
  };
  // 抬起
  document.onmouseup = function () {
    document.onmousemove = null;
    document.onmouseup = null;
  };
};
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.