
마우스 메소드 활용
자바스크립트의 기능을 이용하여 웹페이지에 동적인 기능 중 마우스 관련 메소드를 활용하여 상자에서 색을 드래그 하여 다른 상자에 입힐 수 있는 기능을 구현 해보자.
drag.html
<!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>
.container {
width: 400px;
height: 400px;
border: 1px solid;
display: flex;
flex-wrap: wrap;
}
.box {
width: 200px;
height: 200px;
border: 1px solid red;
box-sizing: border-box;
}
#item {
width: 100%;
height: 100%;
background-color: blue;
}
</style>
</head>
<body>
<div class="container">
<div class="box">
<!-- 드래그를 허용해 주는 속성을 true false로 설정 -->
<div id="item" class="item" draggable="true"></div>
</div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</body>
<script src="./drag.js"></script>
</html>
drag.js
let _target = null;
// ondragstart : 드래그가 시작될떄 실행되는 이벤트
document.ondragstart = function (e) {
if (e.target.classList.contains("item")) {
console.log(e.target);
_target = e.target;
// 태그에 스타일 값을 추가
e.target.style.backgroundColor = "red";
}
};
// ondragend : 드래그가 끝날때 실행되는 이벤트
document.ondragend = function (e) {
_target = null;
// e.target이 item 클래스를 가지고 있는 태그라면
if (e.target.classList.contains("item")) {
// 처음에 입혀줬던 색으로 다시 변경
e.target.style.backgroundColor = "blue";
}
};
// ondragenter : 드래그하고 태그위에 올려졌을때 실행되는 이벤트
document.ondragenter = function (e) {
// e.target이 box 클래스를 가지고 있고 _target이 비어있지 않을때 실행
if (e.target.classList.contains("box") && _target !== null) {
e.target.style.backgroundColor = "yellow";
}
};
// ondragleave : 드래그 하는중 태그에서 빠져나갔을때 실행되는 이벤트
document.ondragleave = function (e) {
if (e.target.classList.contains("box") && _target !== null) {
e.target.style.backgroundColor = "transparent";
}
};
// ondropover : 대상의 드롭 가능 여부 설정
document.ondragover = function (e) {
if (e.target.classList.contains("box") && _target !== null) {
// preventDefault : 브라우저에서 기본적으로 동작하는 기능을 제거
e.preventDefault();
}
};
// ondrop : 드래그를 하다 마우스 버튼을 때면 드롭
document.ondrop = function (e) {
if (e.target.classList.contains("box") && _target !== null) {
e.target.style.backgroundColor = "transparent";
e.target.append(_target);
}
};
- 파란 네모를 클릭하여 드래그엔 드랍으로 다른 상자에 색을 옮길 수 있다.
728x90
'JavaScript' 카테고리의 다른 글
| [Javascript] cookie를 활용한 팝업창 만들기 (0) | 2023.03.27 |
|---|---|
| [Javascript] localstorage를 활용한 todolist 만들기 (0) | 2023.03.27 |
| [Javascript] 생성자 함수와 자주쓰는 DOM, BOM 메소드 (0) | 2023.03.21 |
| [Javascript] callback 함수를 활용한 일반 함수와 화살표 함수 사용 및 this의 차이점 알아보기 (0) | 2023.03.16 |
| [Javascript] 배열 함수를 활용한 로또 번호 생성기 만들기 (2) | 2023.03.15 |