[javascript] DOM을 이용한 이벤트 처리

이상원·2023년 11월 10일

html/css/javascript

목록 보기
7/8

버튼을 클릭해서 글자색 바꾸기

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>자바스크립트 이벤트</title>
	<link rel="stylesheet" href="css/function.css">
</head>
<body>
	<button id="change">글자색 바꾸기</button>	
	<p>Reprehenderit tempor do quis sunt eu et exercitation deserunt. Laboris adipisicing est sint aliquip nulla pariatur velit irure elit qui id. Dolore aliquip dolore eu ut irure sint Lorem reprehenderit velit. Duis veniam irure cillum anim excepteur culpa pariatur sunt esse. Eu nulla commodo velit ex id dolore incididunt mollit incididunt nisi labore culpa qui ea. Commodo veniam veniam in ipsum ad minim occaecat qui pariatur adipisicing laborum quis.</p>
	
	<script>
    // 방법 1 : 웹 요소를 변수로 지정 & 미리 만든 함수 사용
    var changeBttn = document.querySelector("#change");
    changeBttn.onclick = changeColor;
    
		function changeColor() {
      document.querySelector("p").style.color = "#f00";
    }
   
    // 방법 2 : 웹 요소를 따로 변수로 만들지 않고 사용
    document.querySelector("#change").onclick = changeColor;

		function changeColor() {
      document.querySelector("p").style.color = "#f00";
    }
    
    // 방법 3 : 직접 함수를 선언
    document.querySelector("#change").onclick = function() {
      document.querySelector("p").style.color = "#f00";
    };

		

	</script>
</body>
</html>  

버튼을 클릭해서 설명글 열고 닫기

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>자바스크립트 이벤트</title>
	<link rel="stylesheet" href="css/event.css">
</head>
<body>
	<div id="item">
		<img src="images/flower.jpg" alt="">
		<button class="over" id="open">상세 설명 보기</button>
		<div id="desc" class="detail">
			<h4>등심붓꽃</h4>
			<p>북아메리카 원산으로 각지에서 관상초로 흔히 심고 있는 귀화식물이다. 길가나 잔디밭에서 흔히 볼 수 있다. 아주 작은 씨앗을 무수히 많이 가지고 있는데 바람을 이용해 씨앗들을 날려보내거나, 뿌리줄기를 통해 동일한 개체들을 많이 만들어 냄으로써 번식한다. </p>
			<button id="close">상세 설명 닫기</button>
		</div>
	</div>	

	<script>		
		document.querySelector('#open').onclick = function() {
			document.querySelector('#desc').style.display = "block";	// 상세 설명 부분을 화면에 표시
			document.querySelector('#open').style.display = "none";   // '상세 설명 보기' 단추를 화면에서 감춤
		}
		document.querySelector('#close').onclick = function() {
			document.querySelector('#desc').style.display = "none";	   // 상세 설명 부분을 화면에서 감춤
			document.querySelector('#open').style.display = "block";	 // '상세 설명 보기' 단추를 화면에 표시
		}				
	</script>
</body>
</html>  

버튼을 클릭해서 이미지 바꾸기

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>DOM event 객체</title>
  <style>
    #container {
      width:300px;
      margin:10px auto;
    }
  </style>
</head>
<body>
  <div id="container">
    <img src="images/cup-1.png" id="cup">		
  </div>

	<script>
		var cup = document.querySelector("#cup");  // id = cup인 요소를 가져옴
    cup.onclick = changePic;  // cup을 클릭하면 changePic 함수 실행
    var a =1 
    function changePic() {
      if (a==1){
        cup.src = "images/cup-2.png";
        a=2
      } else{
        cup.src = "images/cup-1.png";
        a=1
      }
      
      
		}
	</script>
</body>
</html>

addEventListener

addEventListener()와 event 객체를 사용하면 한 요소에 여러 이벤트 처리기를 연결해 실행할 수 있다.
addEventListener() 메서드의 끝에는 세미콜론이 필수다.

  • 기본형
요소.addEventListener(이벤트, 함수, 캡처 여부);
//이벤트 > 이벤트 유형 지정, click/keypress 처럼 on을 붙이지 않고 써야함
//함수 > 이벤트가 발생하면 실행할 명령이나 함수를 지정, event 객체를 인수로 받는다.
//캡처 여부 > 이벤트를 캡처하는지 여부를 지정, 기본값은 false

캡처 여부가 true이면 캡처링, false면 버블링한다는 의미
캡처링: 부모 노드에서 자식 노드로 전달
버블링: 자식 노드에서 부모 노드로 전달

  • 마우스 포인터를 올리면 이미지 바꾸기
<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>DOM event 객체</title>
  <style>
    #container {
      width:300px;
      margin:10px auto;
    }
  </style>
</head>
<body>
	<div id="container">
		<img src="images/easys-1.jpg" id="cover">	
  </div>
  
	<script>
		var cover = document.getElementById("cover");
		cover.addEventListener("mouseover",changePic, false);
    cover.addEventListener("mouseout",originPic, false);
    
    function changePic() {
      cover.src = "images/easys-2.jpg";
    }
    function originPic() {
      cover.src = "images/easys-1.jpg";
    }
	</script>
</body>
</html>

css 속성에 접근하기

  • id가 desc인 요소의 글자색 바꾸기
document.getElementById("desc").style.color = "blue";

style 예약어를 사용하여 접근한다.

  • 도형의 테두리와 배경색 바꾸기
<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>DOM CSS</title>
	<style>
		#container {
			width:400px;
			margin:50px auto;
			text-align: center;
		}
		#rect {
			width:100px;
			height:100px;			
			border:1px solid #222;
			margin:30px auto;
			transition: 1s;
		}
	</style>
</head>
<body>
	<div id="container">
		<p>도형 위로 마우스 포인터를 올려놓으세요.</p>
		<div id="rect"></div>
	</div>	
	
	<script>
		var myRect = document.querySelector("#rect");
		myRect.addEventListener("mouseover", function() {  // mouseover 이벤트 처리
			myRect.style.backgroundColor = "green";  // myRect 요소의 배경색 
			myRect.style.borderRadius = "50%";  // myRect 요소의 테두리 둥글게 처리
		});
		myRect.addEventListener("mouseout", function() {  // mouseout 이벤트 처리
			myRect.style.backgroundColor = "";  // myRect 요소의 배경색 지우기 
			myRect.style.borderRadius = "";  // myRect 요소의 테두리 둥글게 처리 안 함
		});
	</script>
</body>
</html>
profile
Sang9riG9ru

0개의 댓글