티스토리 뷰

1.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>NomadCode JS Chrome App</title>
</head>
<body>
<div>
<h1 class="hello">Grab Me!</h1>
<h1 class="hello">Grab Me!</h1>
<h1 class="hello">Grab Me!</h1>
</div>
<script>
const h1 = document.querySelector('div .hello:first-child');
function handleTitleClick() {
const currentColor = h1.style.color;
let newColor;
if (currentColor === 'blue') {
newColor = 'tomato';
} else {
newColor = 'blue';
}
h1.style.color = newColor;
}
h1.addEventListener('click', handleTitleClick);
</script>
</body>
</html>
변수 2가지 currentColor와 newColor 의 역할에 대해서 알아봅시다.
1. currentColor는 getter로써, 최근 color값을 복사하는 역할. 그렇기에 의미론적const로 선언.
2. newColor는 setter로써, 변수에 대입된 색상값을 h1.style.color에 최종적으로 할당하는 역할. 의미론적으로 봤을 때 값이 변경될 수 있기에 let으로 선언하는 것이 적절.
3. (참고) 함수 내에서 선언된 변수는 함수 밖에서는 존재하지 않습니다. 그렇기 때문에 const currentColor로 변수 선언을 하더라도, 함수가 호출될 때 마다 새로운 값을 받을 수 있습니다.
실행순서
1) click event 발생 및 함수 실행
2) currentColor 변수 선언 후 h1.style.color 값 복사 (getter)
3) newColor 변수 선언
4) currentColor 현재 값 확인
5) 조건에 따라 newColor에 "tomato" or "blue" 값 대입
6) 마지막으로 h1.style.color에 newColor값 대입 (setter)
아래는 코드 실행시 화면
2.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>NomadCode JS Chrome App</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style>
h1 {
color: blue;
transition: color 0.5s ease-in-out;
}
.clicked {
color: tomato;
}
</style>
</head>
<body>
<div>
<h1 class="hello">Grab Me!</h1>
<h1 class="hello">Grab Me!</h1>
<h1 class="hello">Grab Me!</h1>
</div>
<script>
const h1 = document.querySelector('div .hello:first-child');
function handleTitleClick() {
const clickedClass = 'clicked'; //아래에서 오류를 줄이기 위한 getter 변수 이다.
if (h1.className === clickedClass) {
h1.className = '';
} else {
h1.className = clickedClass;
}
}
h1.addEventListener('click', handleTitleClick);
</script>
<script src="script.js"></script>
</body>
</html>
Grab Me!
Grab Me!
Grab Me!
'WEB > JavaScript' 카테고리의 다른 글
| [크롬 앱 만들기] #4.1 Form Submission | form -> submit (0) | 2022.01.16 |
|---|---|
| [크롬 앱 만들기] #3.8 css in js | toggle function (0) | 2022.01.16 |
| [제로초JS] chap8 반응속도테스트 (0) | 2022.01.14 |
| [제로초JS] chap7 가위바위보 (0) | 2022.01.13 |
| var와 let 차이 이해하기 (0) | 2022.01.13 |
댓글