자바스크립트 마우스 이벤트: 클릭, 더블 클릭, 오버, 아웃, 이동, 휠

자바스크립트 마우스 이벤트: 클릭, 더블 클릭, 오버, 아웃, 이동, 휠

자바스크립트에서 마우스 이벤트는 웹 페이지에서 마우스와 관련된 동작을 처리하는 데 사용됩니다. 이러한 이벤트를 사용하면 사용자와 상호 작용하는 동적인 웹 페이지를 만들 수 있습니다. 이번 글에서는 클릭, 더블 클릭, 마우스 오버와 아웃, 이동, 휠 이벤트를 처리하는 방법에 대해서 예제로 알아보겠습니다.

1. 마우스 이벤트 종류

▼ 마우스 이벤트

이벤트 종류이벤트 설명
click요소를 클릭할 때 발생합니다.
dblclick요소를 빠르게 두 번 클릭할 때 발생합니다.
mouseover마우스가 요소 위로 올라갈 때 발생합니다.
mouseout마우스가 요소에서 벗어날 때 발생합니다.
mousemove마우스를 움직일 때 발생합니다.
wheel마우스 휠을 스크롤할 때 발생합니다.

2. 예제 1: 클릭, 더블 클릭, 오버, 아웃 이벤트

1. 예제 코드

<!DOCTYPE html>
<html>

<head>
     <title>마우스 이벤트 예시1</title>
     <style>
     button {
     display: block;
     margin-bottom: 10px;
     }
     </style>
</head>

<body>

     <button id="button1">click 이벤트</button>
     <button id="button2">dblclick 이벤트</button>
     <button id="button3">mouseover, mouseout 이벤트</button>

     <script>
     
     // 1. click 이벤트
     const button1 = document.getElementById("button1");
     button1.addEventListener("click", () => {
     alert("버튼이 클릭되었습니다!");
     });

     // 2. dblclick 이벤트
     const button2 = document.getElementById("button2");
     button2.addEventListener("dblclick", () => {
     alert("버튼이 더블 클릭되었습니다!");
     });

     // 3. mouseover 이벤트
     const button3 = document.getElementById("button3");
     button3.addEventListener("mouseover", () => {
     button3.style.backgroundColor = "red";
     });

     // 4. mouseout 이벤트
     button3.addEventListener("mouseout", () => {
     button3.style.backgroundColor = "";
     });
     
     </script>
</body>

</html>

2. 실행 결과 화면

클릭, 더블 클릭, 오버, 아웃 이벤트 예제 실행 결과 화면입니다.

3. 예제 2: 마우스 이동 및 휠 이벤트

1. 예제 코드

<!DOCTYPE html>
<html>

<head>
     <title>마우스 이벤트 예시2</title>
     <style>
     .box {
     width: 100px;
     height: 100px;
     background-color: blue;
     position: absolute;
     }
     </style>
</head>

<body>

     <div id="box" class="box"></div>

     <script>
     // 5. mousemove 이벤트: 마우스 이동시 박스 따라 움직이기
     document.addEventListener("mousemove", (event) => {
     box.style.left = event.clientX + "px";
     box.style.top = event.clientY + "px";
     });

     // 6. wheel 이벤트: 마우스 휠 이벤트시 박스 크기 조정하기
     document.addEventListener("wheel", (event) => {
     const delta = Math.sign(event.deltaY);
     const newSize = Math.max(20, box.clientWidth + delta * 10);
     box.style.width = newSize + "px";
     box.style.height = newSize + "px";
     });
     </script>
</body>

</html>

2. 실행 결과 화면

마우스 이동 및 휠 이벤트 예제 실행 결과 화면입니다.

함께 보면 좋은 게시글

이 글이 도움이 되셨다면 공유 부탁 드립니다.

위로 스크롤