오늘은 웹 페이지 주간모드, 야간모드 적용시 링크 색깔도 변경하는 방법을 배웠다.
이전 포스팅에서 만든 웹사이트의 주간모드와 야간모드의 모습이다.
야간모드를 적용했을 때 링크 색깔이 잘 보이지 않아서 더 선명한 색으로 변경하려고 한다.
<body>
<h1><a href="index.html">WEB</a></h1>
<input id ="night_day" type="button" value="night" onclick="
var target = document.querySelector('body');
if (this.value ==='night'){
target.style.backgroundColor='black';
target.style.color='white';
this.value ='day';
}
else {
target.style.backgroundColor='white';
target.style.color='black';
this.value ='night';
}
">
이전에 사용했던 코드이다.
방법은 if문과 else 문에 코드를 추가하는 것이다.
추가하는 코드는 아래와 같다.
var alist = document.querySelectorAll('a');
var i = 0;
while(i<alist.length){
alist[i].style.color='powderblue';
i = i+1;
document.querySelectorAll();는 javascript get element by css selector multiple 속성이다.
document.querySelectorAll()을 사용하여 CSS에서 웹 페이지의 모든 <a> 태그를 가져와서 링크 배열을 선언한 후 반복문을 통해 링크의 색깔을 모두 변경하는 방식이다.
else 문에 추가한 코드
var alist = document.querySelectorAll('a');
var i = 0;
while(i<alist.length){
alist[i].style.color='blue';
i = i+1;
링크 색깔만 변경해주면된다.
<body>
<h1><a href="index.html">WEB</a></h1>
<input id ="night_day" type="button" value="night" onclick="
var target = document.querySelector('body');
if (this.value ==='night'){
target.style.backgroundColor='black';
target.style.color='white';
this.value ='day';
var alist = document.querySelectorAll('a');
var i = 0;
while(i<alist.length){
alist[i].style.color='powderblue';
i = i+1;
}
}
else {
target.style.backgroundColor='white';
target.style.color='black';
this.value ='night';
var alist = document.querySelectorAll('a');
var i = 0;
while(i<alist.length){
alist[i].style.color='blue';
i = i+1;
}
}
">
</body>
적용한 모습이다.
'소프트웨어 > JavaScript' 카테고리의 다른 글
[JavaScript] 객체 기본 개념 예제 (0) | 2023.02.03 |
---|---|
[JavaScript] 함수 활용한 refactoring - 야간 모드 예제 간결하게 (0) | 2023.02.02 |
[JavaScript] 중복 제거를 위한 refactoring - 야간모드 예제 코드 간결하게 (0) | 2023.01.31 |
[JavaScript] 웹 페이지 야간모드 만들기 기초 - 하나의 버튼으로 (0) | 2023.01.31 |
[JavaScript] 웹 페이지 야간모드 만들기 기초 예제 (0) | 2023.01.30 |