• 회원가입
  • 로그인
  • 구글아이디로 로그인

[js] JS - Drag & Drop (= Draggable) - 요소이동 (= 요소끌어이동 = 드래그앤드롭 = 드래거블)

Drag & Drop 예제 

 

<style>

#hz {

  position: absolute;

  z-index: 9;

  text-align: left;

  border: 1px solid silver;

}

 

#hz p {padding:5px;}

 

#hzheader {

  padding: 10px;

  cursor: move;

  z-index: 10;

  background-color: #2196F3;

  color: #fff;

}

</style>


<div id="hz">

  <div id="hzheader">이동하려면 여기 클릭</div>

  <p>홈짱닷컴</p>

  <p>Homzzang.com</p>

  <p>홈페이지 제작관리강의</p>

</div>


<script>

// 드래그 가능한 요소 생성

dragElement(document.getElementById("hz"));


function dragElement(elmnt) {

  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;

  // 이동 목적지

  if (document.getElementById(elmnt.id + "header")) {

    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;

  } else {

    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;

  }

}

</script>

 

결과보기

관련글 https://homzzang.com/b/jquery-282

 

방문 감사합니다. (즐겨찾기 등록: Ctrl + D)

분류 제목
게시물이 없습니다.
목록
찾아주셔서 감사합니다. Since 2012