HTML:Drag
Libraries
드래그 앤 드롭 이벤트
마우스로 객체(object)를 드래그해서 놓을 때까지 여러 단계의 이벤트가 순차적으로 발생하게 됩니다.
다음 표는 드래그 앤 드롭시 일어나는 이벤트를 순서대로 보여줍니다.
이벤트 | 설명 |
dragstart | 사용자가 객체(object)를 드래그하려고 시작할 때 발생함. |
dragenter | 마우스가 대상 객체의 위로 처음 진입할 때 발생함. |
dragover | 드래그하면서 마우스가 대상 객체의 위에 자리 잡고 있을 때 발생함. |
drag | 대상 객체를 드래그하면서 마우스를 움직일 때 발생함. |
drop | 드래그가 끝나서 드래그하던 객체를 놓는 장소에 위치한 객체에서 발생함. |
dragleave | 드래그가 끝나서 마우스가 대상 객체의 위에서 벗어날 때 발생함. |
dragend | 대상 객체를 드래그하다가 마우스 버튼을 놓는 순간 발생함. |
DataTransfer 객체
드래그 앤 드롭 이벤트를 위한 모든 이벤트 리스너 메소드(event listener method)는 DataTransfer 객체를 반환합니다.
이렇게 반환된 DataTransfer 객체는 드래그 앤 드롭 동작에 관한 정보를 가지고 있게 됩니다.
draggable 속성
웹 페이지 내의 모든 요소는 draggable
속성을 사용하여 드래그될 수 있는 객체(draggable object)로 변환될 수 있습니다.
ondragstart 속성
드래그될 수 있는 객체로 만든 후에는 ondragstart
속성을 통해 DataTransfer 객체의 setData()
메소드를 호출합니다.
setData()
메소드는 드래그되는 대상 객체의 데이터(data)와 타입(data type)을 설정합니다.
ondragover 속성
ondragover
속성은 드래그되는 대상 객체가 어느 요소 위에 놓일 수 있는지를 설정합니다.
기본적으로 HTML 요소는 다른 요소의 위에 위치할 수 없습니다.
따라서 다른 요소 위에 위치할 수 있도록 만들기 위해서는 놓일 장소에 있는 요소의 기본 동작을 막아야만 합니다.
이 작업을 event.preventDefault()
메소드를 호출하는 것만으로 간단히 설정할 수 있습니다.
ondrop 속성
드래그하던 객체를 놓으면 Drop 이벤트가 발생합니다.
ondrop
속성을 이용하여 Drop 이벤트에 대한 동작을 설정할 수 있습니다.
Event How to
function dragEnter(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
Examples
윈도우 스타일의 창 이동 (직접 구현)
<div class="window">
<div class="titlebar">Hello, World!</div>
<div class="content">
<p>Window <b>Content!</b></p>
</div>
</div>
// For each item with a `window` class…
var windows = document.querySelectorAll('.window');
[].forEach.call(windows,function(win){
// …find the title bar inside it and do something onmousedown
var title = win.querySelector('.titlebar');
title.addEventListener('mousedown',function(evt){
// Record where the window started
var real = window.getComputedStyle(win),
winX = parseFloat(real.left),
winY = parseFloat(real.top);
// Record where the mouse started
var mX = evt.clientX,
mY = evt.clientY;
// When moving anywhere on the page, drag the window
// …until the mouse button comes up
document.body.addEventListener('mousemove',drag,false);
document.body.addEventListener('mouseup',function(){
document.body.removeEventListener('mousemove',drag,false);
},false);
// Every time the mouse moves, we do the following
function drag(evt){
// Add difference between where the mouse is now
// versus where it was last to the original positions
win.style.left = winX + evt.clientX-mX + 'px';
win.style.top = winY + evt.clientY-mY + 'px';
};
},false);
});
body { background:#eee }
.window {
position:absolute;
top:20px; left:30px; width:200px; height:150px;
border:1px solid #ddd;
background:#fff;
box-shadow:3px 3px 10px rgba(0,0,0,0.2);
user-select:none;
-webkit-user-select:none;
-moz-user-select:none;
}
.window .titlebar { background:#ddd; text-align:center; cursor:move; border-bottom:1px solid #ccc }
.window .content { padding:1em }
엑셀 스타일의 컬럼 이동
엘리먼트 드래그 이동
.draggable {
/* Indicate the element draggable */
cursor: move;
/* It will be positioned absolutely */
position: absolute;
/* Doesn't allow to select the content inside */
user-select: none;
}
// The current position of mouse
let x = 0;
let y = 0;
// Query the element
const ele = document.getElementById('dragMe');
// Handle the mousedown event
// that's triggered when user drags the element
const mouseDownHandler = function(e) {
// Get the current mouse position
x = e.clientX;
y = e.clientY;
// Attach the listeners to `document`
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
};
const mouseMoveHandler = function(e) {
// How far the mouse has been moved
const dx = e.clientX - x;
const dy = e.clientY - y;
// Set the position of element
ele.style.top = `${ele.offsetTop + dy}px`;
ele.style.left = `${ele.offsetLeft + dx}px`;
// Reassign the position of mouse
x = e.clientX;
y = e.clientY;
};
const mouseUpHandler = function() {
// Remove the handlers of `mousemove` and `mouseup`
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
ele.addEventListener('mousedown', mouseDownHandler);