<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
background: darksalmon;
}
.fill {
background-image: url('https://source.unsplash.com/random/150x150');
position: relative;
height: 150px;
width: 150px;
top: 5px;
left: 5px;
cursor: pointer;
}
.hold {
border: solid 5px #ccc;
}
.empty {
display: inline-block;
height: 160px;
width: 160px;
margin: 10px;
border: solid 3px salmon;
background: white;
}
.hovered {
background: #f4f4f4;
border-style: dashed;
}
</style>
</head>
<body>
<div class="empty">
<div class="fill" draggable="true"> </div>
</div>
<div class="empty">
</div>
<div class="empty">
</div>
<div class="empty">
</div>
<div class="empty">
</div>
<script>
const fill = document.querySelector('.fill');
const empties = document.querySelectorAll('.empty');
// Fill listeners
fill.addEventListener('dragstart', dragStart);
fill.addEventListener('dragend', dragEnd);
// Loop through empty boxes and add listeners
for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
// Drag Functions
function dragStart() {
this.className += ' hold';
setTimeout(() => (this.className = 'invisible'), 0);
}
function dragEnd() {
this.className = 'fill';
}
function dragOver(e) {
e.preventDefault();
}
function dragEnter(e) {
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
this.className = 'empty';
}
function dragDrop() {
this.className = 'empty';
this.append(fill);
}
</script>
</body>
</html>
'2022 SW전문인재양성사업 > 웹 프로그래밍 기본' 카테고리의 다른 글
Javascript (8) - prototype, constructor (0) | 2022.07.27 |
---|---|
Javascript (7) - 캐러셀 이미지 슬라이더 실습 (0) | 2022.07.27 |
Javascript (5) - 드래그 앤 드롭 실습1 (0) | 2022.07.27 |
Javascript (4) - 박스 이동 함수 (0) | 2022.07.27 |
Javascript (3) - 드래그 앤 드롭으로 박스 옮기기 (0) | 2022.07.27 |