Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript 및 CSS로 드래그 가능한 HTML 요소를 만드는 방법은 무엇입니까?

<시간/>

JavaScript와 CSS로 드래그 가능한 HTML 요소를 생성하기 위한 코드는 다음과 같습니다 -

예시

<!DOCTYPE html>
<html>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .dragDiv {
      position: absolute;
      z-index: 9;
      text-align: center;
      border: 1px solid #d3d3d3;
      padding: 30px;
      cursor: move;
      z-index: 10;
      background-color: rgb(108, 24, 177);
      color: #fff;
      font-size: 20px;
      font-weight: 500;
   }
</style>
<body>
<h1>Draggable DIV Element Example</h1>
<h2>Click and drag the below element to move it around</h2>
<div class="dragDiv">
This div can be moved around
</div>
<script>
   dragElement(document.querySelector(".dragDiv"));
   function dragElement(ele) {
      var pos1 = 0,
      pos2 = 0,
      pos3 = 0,
      pos4 = 0;
      if (document.querySelector(ele.id + "header")) {
         document.getElementById(
            ele.id + "header"
         ).onmousedown = dragMouseDown;
      }
      else {
         ele.onmousedown = dragMouseDown;
      }
      function dragMouseDown(e) {
         e = e || window.event;
         e.preventDefault();
         pos3 = e.clientX;
         pos4 = e.clientY;
         document.onmouseup = closeDragElement;
         document.onmousemove = elementDrag;
      }
      function elementDrag(e) {
         e = e || window.event;
         e.preventDefault();
         pos1 = pos3 - e.clientX;
         pos2 = pos4 - e.clientY;
         pos3 = e.clientX;
         pos4 = e.clientY;
         ele.style.top = ele.offsetTop - pos2 + "px";
         ele.style.left = ele.offsetLeft - pos1 + "px";
      }
      function closeDragElement() {
         document.onmouseup = null;
         document.onmousemove = null;
      }
   }
</script>
</body>
</html>

출력

위의 코드는 다음 출력을 생성합니다 -

JavaScript 및 CSS로 드래그 가능한 HTML 요소를 만드는 방법은 무엇입니까?

드래그하여 div를 이동할 때 -

JavaScript 및 CSS로 드래그 가능한 HTML 요소를 만드는 방법은 무엇입니까?