1. Style
.dragContainer {
background-color: #333;
height: auto;
padding: 1rem;
margin-top: 1rem;
}
.draggable {
padding: 1rem;
background-color: white;
border: 1px solid black;
cursor: move;
}
.draggable .dragging {
opacity: .5;
}
2. HTML
<div id="itemBox1" class="dragContainer">
<p id="itemTag1" class="draggable" draggable="true">1</p>
<p id="itemTag2" class="draggable" draggable="true">2</p>
</div>
<div id="itemBox2" class="dragContainer">
<p id="itemTag3" class="draggable" draggable="true">3</p>
<p id="itemTag4" class="draggable" draggable="true">4</p>
</div>
<button onclick="TestFunction()">Test Button</button>
3. Script
const draggables = document.querySelectorAll('.draggable');
const containers = document.querySelectorAll('.dragContainer');
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging');
})
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging');
})
});
containers.forEach(container => {
container.addEventListener('dragover', (e) => {
e.preventDefault();
const afterElement = getDragAfterElement(container, e.clientY);
const draggable = document.querySelector('.dragging');
if( afterElement == null) {
container.appendChild(draggable);
} else {
container.insertBefore(draggable, afterElement);
}
})
});
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')];
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2
if(offset < 0 && offset > closest.offset) {
return { offset: offset, element: child}
} else {
return closest;
}
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
function TestFunction () {
for(let index = 0; index < document.getElementById('itemBox2').children.length; index++) {
console.log(document.getElementById('itemBox2').children[index]);
}
}
2개의 div 박스에서 드래그 앤 드랍으로 아이템을 이동시킬수 있습니다.
버튼을 눌러 2번째 박스에 있는 아이템들을 콘솔로 볼수 있습니다.
참고: youtube( Web Dev Simplified )
'Web 공부' 카테고리의 다른 글
웹개발 공부 - 1. 프로젝트를 만들어보자 (0) | 2022.01.14 |
---|---|
IE(Internet Explorer) 에서 Script(스크립트)가 작동하지 않을때 (0) | 2020.11.17 |
JavaScript - 차트(chart)를 이미지화 시켜서 Excel 로 내보내기(export) (0) | 2020.11.17 |
비주얼 스튜디오 코드(Visual Studio Code) -초간단 한글 설정 (0) | 2020.11.16 |