본문 바로가기
개발 공부 일지/JavaScript

자바스크립트 - 마우스 이벤트

by yelimu 2024. 7. 17.


 [마우스 버튼 이벤트] 

 > MouseEvent.button : 이벤트 객체의 버튼 프로퍼티 
 0: 마우스 왼쪽 버튼
 1: 마우스 휠
 2: 마우스 오른쪽 버튼
 
 > MouseEvent.type  : 이벤트 객체의 타입 프로퍼티 
 click: 마우스 왼쪽 버튼을 눌렀을 때
 contextmenu: 마우스 오른쪽 버튼을 눌렀을 때
 dblclick: 동일한 위치에서 빠르게 두번 click할 때
 mousedown: 마우스 버튼을 누른 순간
 mouseup: 마우스 버튼을 눌렀다 뗀 순간

 

하나의 동작이라고 생각되더라도 여러가지 이벤트가 발생할 수 있다. (운영체제에 따라 순서도 달라질 수 있음)

 

왼쪽 버튼 클릭 (총 3개 이벤트 발생)

mousedown

mouseup

click

 

왼쪽 더블클릭 했을때 (총 7개 이벤트 발생) 

mousedown

mouseup

click

mousedown

mouseup

click

dbclick

 


[마우스 이동 이벤트]
  > MouseEvent.type
  mousemove: 마우스 포인터가 이동할 때
  mouseover: 마우스 포인터가 요소 밖에서 안으로 이동할 때
  mouseout: 마우스 포인터가 요소 안에서 밖으로 이동할 때 
 
  > MouseEvent.clientX, clientY
  : 화면에 표시되는 창 기준 마우스 포인터 위치   
  
  > MouseEvent.pageX, pageY
  : 웹 문서 전체 기준 마우스 포인터 위치
  
  > MouseEvent.offsetX, offsetY
  : 이벤트가 발생한 요소 기준 마우스 포인터 위치


mousemove

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

const box1 = document.querySelector('#box1');

 

function onMouseMove() {

  console.log('mouse is moving');

}

 

function onMouseMove() {

  console.log('client: (${e.clientX}, ${e.clientY})');           화면에 표시되는 창에서의 위치 정보

  console.log('page: (${e.page}, ${e.page})');                 전체 문서에서의 위치 정보

  console.log('offset: (${e.offset}, ${e.offset})');               이벤트가 적용되는 요소 내에서의 위치 정보

}

 

box1.addEventListener('mousemove', onMouseMove);

box1 요소에 

mousemove 이벤트 발생 시

onMouseMove 이벤트 핸들러를 동작한다


  mouseover & mouseout

<div id="box2" class="box">
    <div id="cell-1" class="cell">cell-1</div>
    <div id="cell-2" class="cell">cell-2</div>
    <div id="cell-3" class="cell">cell-3</div>
    <div id="cell-4" class="cell">cell-4</div>
</div>

 

const box2 = document.querySelector('#box2');

 

function printEventData(e){

  console.log(e.type): }         이벤트 타입을 출력해주는 이벤트 핸들러

 

box2.addEventListener('mouseover', printEventData);

box2.addEventListener('mouseout', printEventData);

 

box2 요소에 

mouseover / mouseout 이벤트가 발생하면 

printEventData 함수를 동작한다

 

이벤트 핸들러를 아래와 같이 수정하면

function printEventData(e){

  if (e.target.classList.contains('cell')){

       e.target.classList.toggle('on');

  }

}

if 이벤트 타겟의 class 가 cell을 포함하면 

이벤트 타켓에 .on class를 토글해라


> MouseEvent.target

: 이벤트가 발생한 요소

 

> MouseEvent.relatedTarget

: 이벤트가 발생하기 직전(또는 직후)에 마우스가 위치해있던 요소 

 

이 두 가지로 경로를 파악할 수 있다


mouseover/mouseout : 자식요소에까지 영향을 끼친다 (버블링 ㅇ)

mouseenter/mouseleave : 자식요소에 영향을 끼치지 않고 해당 요소에만 이벤트 핸들러를 다룰 수 있다 (버블링x)