다크모드와 일반모드라는 두 가지 모드를 통해 웹페이지의 배경과 폰트 색상을 제어해보자. 1차원적인 방법에서 시작하여 조건문을 활용한 방법을 거쳐, 최종적으로는 코드 리팩토링을 통해 유지와 보수가 쉽도록 바꾸어보자.
<h1><a href="index.html">스타일 제어하기</a></h1>
<input type="button" value="다크모드" onclick="
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
">
<input type="button" value="일반모드" onclick="
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
">
<ol>
<li><a href="1.html">HTML</a></li>
<li><a href="2.html">CSS</a></li>
<li><a href="3.html">JavaScript</a></li>
</ol>
<div>
본문 내용이 들어가는 곳입니다. 버튼을 누르면 글자색과 배경색이 바뀝니다
</div>
<h1><a href="index.html">조건문으로 제어</a></h1>
<input id="themeStatus" type="button" value="다크모드" onclick="
if(document.querySelector('#themeStatus').value === '다크모드'){
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#themeStatus').value = '일반모드';
} else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#themeStatus').value = '다크모드';
}
">
<ol>
<li><a href="1.html">HTML</a></li>
<li><a href="2.html">CSS</a></li>
<li><a href="3.html">JavaScript</a></li>
</ol>
<h2>JavaScript</h2>
<p>
연습용 페이지입니다
</p>
.
.
<input id="themeStatus" type="button" value="다크모드" onclick="
if{document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#themeStatus').value = '일반모드';
} else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#themeStatus').value = '다크모드';
}
">
.
.
아래처럼 const 와 this를 사용해보자
onclick 이라는 이벤트 안에서 this는 해당 이벤트가 소속되어 있는 태그를 가리키도록 약속되어 있다
<h1>this의 활용</h1>
<input id="themeStatus" type="button" value='다크모드' onclick="
const target = document.querySelector('body');
if(this.value === '다크모드'){
target.style.backgroundColor = 'black';
target.style.color = 'white';
this.value = '일반모드';
} else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
this.value = '다크모드';
}
">
<ol>
<li><a href="1.html">HTML</a></li>
<li><a href="2.html">CSS</a></li>
<li><a href="3.html">JavaScript</a></li>
</ol>
<h2>JavaScript</h2>
<p>
리팩토링!
</p>