JavaScript
[JavaScript] 마우스 드래그로 일괄 선택하기
teamnova
2023. 3. 31. 12:00
728x90
안녕하세요. 이번 시간에는 마우스 드래그를 통해 한번에 이벤트를 발생시키는 방법에 대해 알아보겠습니다.
자바스크립트에는 마우스와 관련된 다양한 이벤트를 제공하는데, 아래의 예제에서는 mousedown(마우스를 누르고 있을 때), mousemove(마우스를 움직일 때), mouseup(마우스를 뗄 때) 이 세 가지를 사용하여 드래그를 했을 때 버튼 색깔을 바꾸는 방식입니다.
index.php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script defer = "defer" src = "./index.js"></script>
</head>
<style>
.btn {
background-color : gray;
border-radius : 1rem;
font-size : 12px;
line-height : 16px;
padding : 8px;
margin : 1px;
text-align : center;
width: 80px;
}
</style>
<body>
<button id = "1" class = "btn">버튼1</button>
<button id = "2" class = "btn">버튼2</button>
<button id = "3" class = "btn">버튼3</button>
<button id = "4" class = "btn">버튼4</button>
<button id = "5" class = "btn">버튼5</button>
</body>
</html>
index.js
for (const button of document.querySelectorAll('.btn')) {
mouseMove(button, function (event) {
// 드래그했을 때 해당 부분이 버튼이 아닐 경우에는 return
if (!(event.target instanceof HTMLButtonElement)) return;
// 드래그한 커서가 버튼 위에 갈 경우 빨간색으로 표시
event.target.style.backgroundColor = 'red';
});
// 버튼 클릭했을 때 이벤트
button.addEventListener('click', (event) => {
clickEvent(event);
})
}
function mouseMove(target, whileMove) {
let endMove = function () {
// 마우스를 뗄 때 이벤트 리스너 제거
window.removeEventListener('mousemove', whileMove);
window.removeEventListener('mouseup', endMove);
};
// 마우스를 클릭한 채 움직이면 이벤트리스너 생성
target.addEventListener('mousedown', function (event) {
event.stopPropagation();
window.addEventListener('mousemove', whileMove);
window.addEventListener('mouseup', endMove);
});
}
// 클릭했을 때 빨간색이면 회색으로, 회색이면 빨간색으로 전환
function clickEvent(event) {
const button = event.target;
if (button.style.backgroundColor == 'red') {
button.style.backgroundColor = 'gray';
}
else {
button.style.backgroundColor = 'red';
}
}
코드 실행영상입니다.