비전공자 개발일기

Draggable DIV 본문

Javascript

Draggable DIV

HiroDaegu 2022. 5. 12. 00:50
728x90
SMALL

 

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>DRAGGABLE DIV</title>
  <link rel="stylesheet" href="style.css">
  <script defer src="main.js"></script>
</head>
<body>
  <div class="box">
    <span>DRAG ME</span>
  </div>
</body>
</html>
body {
  margin: 0;
  height: 100vh;
  background-image: radial-gradient(#e0dada, #dcefb6);
  font-family: Arial, Helvetica, sans-serif;
}

.box {
  position: fixed;
  top: 35%;
  left: 40%;
  background: #eee;
  box-shadow: #999 0px 8px 20px 0px;
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none;
}
(() => {
  class Box {
    constructor() {
      this.box = document.querySelector(".box");
      this.handleMouseDown = this.handleMouseDown.bind(this);

      this.handleMouseUp = this.handleMouseUp.bind(this);

      this.handleMouseMove = this.handleMouseMove.bind(this);
    }
    handleMouseDown() {
      this.box.style.cursor = "move";
      this.box.addEventListener("mouseup", this.handleMouseUp);

      document.body.addEventListener("mousemove", this.handleMouseMove);
      document.body.addEventListener("mouseleave", this.handleMouseUp);
    }
    handleMouseUp() {
      this.box.style.cursor = "default";
      document.body.removeEventListener("mousemove", this.handleMouseMove);
      document.body.removeEventListener("mouseleave", this.handleMouseUp);
    }
    handleMouseMove(e) {
      const boxRect = this.box.getBoundingClientRect();
      this.box.style.top = `${boxRect.top + e.movementY}px`;
      this.box.style.left = `${boxRect.left + e.movementX}px`;
    }
    init() {
      this.box.addEventListener("mousedown", this.handleMouseDown);
    }
  }
  const box = new Box();
  box.init();
})();
728x90
LIST

'Javascript' 카테고리의 다른 글

Random Color Generator  (0) 2022.05.15
3D Gallery  (0) 2022.05.14
Animated Submit BUTTON  (0) 2022.05.10
Lock Animation  (0) 2022.05.05
Alarm Application  (0) 2022.05.02