<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div style="width: 200px;height: 200px;background-color: blue;position: absolute;"></div>
  <script>
  let div = document.querySelector('div');
  let flag = false
  div.addEventListener('mousedown', (e) => {
      flag = true
      let x = e.offsetX;
      let y = e.offsetY;
      document.addEventListener('mousemove', (e) => {
        let _h = window.innerHeight - div.offsetHeight 
        let _w = window.innerWidth - div.offsetWidth
        let div_left = e.clientX - x;
        let div_top = e.clientY - y;
        div_top = Math.min(Math.max(0,div_top),_h)
        div_left = Math.min(Math.max(0,div_left),_w)
        if(flag){
        div.style.top = div_top + 'px';
        div.style.left = div_left + 'px';
      }
      });
  });
  div.addEventListener('mouseup',()=>{
      flag = false
  })
</script>
</body>
</html>