이벤트리스너 - 마우스이벤트(과제1)

장돌뱅이 ·2022년 2월 10일
1
const colors = ["#1abc9c", "#3498db", "#9b59b6", "#f39c12", "#e74c3c"];
const title = document.querySelector("h2");

const superEventHandler = {
 //마우스가 title위로 올라가면 텍스트가 변경
 onMouse: function () {
    document.querySelector("h2").style.color = colors[0];
    title.innerText = "The mouse is here!";
  },

//마우스가 title을 벗어나면 텍스트가 변경
  outMouse: function () {
    document.querySelector("h2").style.color = colors[1];
    title.innerText = "The mouse is gone!";
  },

//마우스를 우클릭하면 title 변경 
  rightClick: function () {
    document.querySelector("h2").style.color = colors[3];
    title.innerText = "That was a right click!";
  },

//브라우저 창의 사이즈가 변하면 title 변경
  resize: function () {
    document.querySelector("h2").style.color = colors[2];
    title.innerText = "You just resized!";
  }
};

title.addEventListener("mouseover", superEventHandler.onMouse);
title.addEventListener("mouseleave", superEventHandler.outMouse);
title.addEventListener("contextmenu", superEventHandler.rightClick);
window.addEventListener("resize", superEventHandler.resize); 
  • 브라우저의 창 사이즈가 변할 경우 이벤트 발생

  • 모든 함수 핸들러는 객체 superEventHandler 내부에 작성했다.

  • 이벤트리스너를 불러올 때, 정의한 이벤트 함수가 이벤트 리스너보다 아래에 있으면 코드가 작동하지 않는다.
    https://developer.mozilla.org/ko/docs/Web/Events

  • windows는 웹 브라우저의 창(window)을 나타내는 객체로, 대부분의 웹 브라우저에서 지원한다.
    innerHeight와 innerWidth 프로퍼티를 이용하면, 브라우저의 창 크기를 설정할 수 있다.

// 이벤트리스너 등록 시 속성 방식
	window.onresize = function () {
 	  document.querySelector("h2").style.color = colors[2];
	  title.innerText = "You just resized!";
	};

//메서드 방식
   window.addEventListener("resize", superEventHandler.resize); 

0개의 댓글