드래그 가능한 HTML 요소를 만드는 방법

JavaScript와 CSS를 사용하여 드래그 가능한 HTML 요소를 만들어 보세요.

동적 드래그 가능한 DIV 요소

여기 클릭하여 드래그

이동

DIV

동적 드래그 가능한 DIV 요소를 생성하십시오

第一步 - HTML 추가:

<!-- 동적 드래그 가능한 DIV -->
<div id="mydiv">
  <!-- 동적 드래그 가능한 DIV와 동일한 이름의 제목 DIV를 포함합니다. -->
  <div id="mydivheader">여기 클릭하여 드래그</div>
  <p>이동</p>
  <p>이</p>
  <p>DIV</p>
</div>

第二步 - CSS 추가:

중요한 스타일은 단 하나입니다: position: absolute;,기타 부분은 귀하가 결정하십시오:

#mydiv {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  border: 1px solid #d3d3d3;
  text-align: center;
}
#mydivheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}

제3단계 - JavaScript 추가:

// DIV 요소를 드래그 가능하게 합니다:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // 존재하면, 제목은 DIV을 이동할 위치입니다:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // 그렇지 않으면, DIV 내의 어떤 위치에서도 DIV을 이동시킵니다:
    elmnt.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;
    // 요소의 새 위치를 설정합니다:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }
  function closeDragElement() {
    // 마우스 버튼 떼 때 이동을 멈춘다:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

직접 시도해 보세요