HTML로 Righter 과 Darker 버튼을 만듬
Darker 버튼을 눌렀을땐 NIGHT MODE처럼 화면을 어둡게 바꾸고
Righter 버튼을 눌렀을땐 밝게 만들려고 했음
두가지 방법으로 실행해 봤다.
1. HTML input type oncilck바로 안에 변수를 바로 넣어서 설정해 주는 방법.
<input type="button" value="Righter" onclick="elem=document.querySelector('body'); elem.style.background ='#fff'; elem.style.color='#000';">
<input type ="button" value ="Darker" onclick=" elem = document.querySelector('body'); elem.style.background = '#000'; elem.style.color = '#fff';">
2. script 안에 function탭을 두가지 만들어서 각자 설정값을 부여하는 방법.
<body>
<input type="button" value="Righter" onclick="Righter()">
<input type ="button" value ="Darker" onclick="Darker()">
</body>
<script type="text/javascript">
function Righter(){
elem=document.querySelector('body');
elem.style.background ='#fff';
elem.style.color='#000';
}
function Darker(){
elem = document.querySelector('body');
elem.style.background = '#000';
elem.style.color = '#fff';
}
</script>
두 방법다 output은 똑같음
RESULT
To do list에도 night, day button을 만들고 싶었다.
<input class="night_mode mode" type="button" value="🌙" onclick="nightshift();">
<input class="day_mode mode" type="button" value="🌞" onclick="dayshift();">
그래서 이렇게 html에 두개의 버튼을 넣어줬다.
두개의 버튼을 눌렀을때 화면이 변하게 하기 위해서 function을 두개 만들어준후 각각 onclick에 대입해줬다.
function nightshift(){
elem = document.querySelector('body');
elem.style.background = '#000';
elem.style.color = '#fff';
elem = document.querySelector('#header');
elem.style.background = '#000';
elem = document.querySelector('.night_mode');
elem.style.background = '#000';
elem = document.querySelector('.day_mode');
elem.style.background = '#000';
}
function dayshift(){
elem = document.querySelector('body');
elem.style.background = '#fff';
elem.style.color = '#000';
elem = document.querySelector('#header');
elem.style.background = '#fff';
elem = document.querySelector('.night_mode');
elem.style.background = '#fff';
elem = document.querySelector('.day_mode');
elem.style.background = '#fff';
}
function에는 버튼을 눌렀을때 각각 배경화면, header, 버튼의 background 색이 변할 수 있도록 설정했다.
달모양 icon을 누르면 이렇게 변하고 해 모양을 누르면 원래대로 돌아온다.
사실 한번 더 누르면 다시 day mode로 돌아오게 하고 싶었는데 아직 잘 못하겠다...
>>해결방법
function nightMode(){
elem = document.querySelector('body')
if(elem.style.background == 'black'){
elem.style.background = 'white';
elem.style. color = 'black';
}
else{
elem.style.background = 'black';
elem.style.color = 'white';
}
}
위에 function은 다 삭제하고 새로운 function을 만들었다.
먼저 body전체를 불러와준다음 if문을 사용해서 body의 배경색이 검은색일때 배경은 하얀색, 글자는 검은색으로 바꾸고 그게 아닐경우 배경색은 검은색 글자는 하얀색으로 바꾼다. 라는 코드를 작성해줬다.
이렇게 하면 button하나로 왔다 갔다 할 수 있음.
'Lecture' 카테고리의 다른 글
3.22 - To do list (1) | 2021.03.22 |
---|---|
3.22 - JS (0) | 2021.03.22 |
3.18 - POSITION (0) | 2021.03.18 |
3.17 (0) | 2021.03.17 |
2021.3.12(Fri) - Assignment (0) | 2021.03.15 |