그럼에도 불구하고

👨‍💻

day / night mode ver_2 본문

JavaScript/Function implementation

day / night mode ver_2

zenghyun 2022. 12. 16. 17:22

 

기존의 day / night mode의 코드를 업그레이드해보자

 

 

 

 

기존 코드 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input { width:100px; height: 80px; font-size: 24px;}
    </style>
</head>
<body>
    <h1>day mode / night mode</h1>
    <input type="button" value="night" id="visual" onclick="toggle()">

    <script>
        let visual = document.getElementById('visual'); 
        let body =  document.querySelector('body');
        
        function toggle() {
            if (  visual.value === 'night'   ){
                body.style.backgroundColor = 'black';
                body.style.color = 'white';
                visual.setAttribute('value','day');
            }
            else {
                body.style.backgroundColor = 'white';
                body.style.color = 'black';
                visual.setAttribute('value','night');
            }
        }
    </script>
</body>
</html>

기존 코드는 기능 수행을 하는 데 있어 문제는 없지만 아쉬운 점이 있다. 

 

바로 아래와 같은 문장이 반복된다는 것이다. 

 

// body.style.backgroundColor 

// body.style.color 

 

 

지금은 코드가 짧아 간단하지만, 만약 엄청나게 긴 문장을 갖고 있었다면 유지 보수하기 어렵다. 

그래서 객체를 만들고, 객체 안 메서드로 배경색과 글자 색을 바꿀 수 있게 만들기로 했다. 

 

<script>
        let Body = {
            setColor: function (color){
                document.querySelector('body').style.color = color; 
            },
            setBackgroundColor: function(color){
                document.querySelector('body').style.backgroundColor = color;
            }
        }

        function toggle(self) {
            if (  self.value === 'night'   ){
                Body.setBackgroundColor('black');
                Body.setColor('white');
                self.value = 'day';
            }
            else {
                Body.setBackgroundColor('white');
                Body.setColor('black');
                self.value = 'night'
            }
        }
 </script>

그리고 기존의 방식처럼 setAttrubute 메서드를 사용하지 않고, button을 onclick 했을 때 toggle 메서드 안에 this를 넣었다. 

 

그 후 script구문 안 toggle메서드에 파라미터로 self라는 값을 넣고 self.value로 value 값을 변경했다. 

 


++ 추가 기능 

 

a 태그를 만들고 버튼을 눌렀을 때 a 태그의 색도 변경하게 만들었다.  

 

 let Link = {
            setColor: function (color) {
            let links = document.querySelectorAll('a');
            for(var i = 0; i< links.length; i++){
                links[i].style.color = color;
            }
        }}

 

 

 

 

최종

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input { width:100px; height: 80px; font-size: 24px;}
        li { list-style: none;}
        li > a { text-decoration: none; color:powderblue}
    </style>
</head>
<body>
    <h1>day mode / night mode</h1>
    <ul>
        <li><a href="a.html">1. 소개</a></li>
        <li><a href="b.html">2. 개요</a></li>
        <li><a href="c.html">3. 위치</a></li>
        <li><a href="d.html">4. 약관</a></li>
    </ul>
    <input type="button" value="night" id="visual" onclick="toggle(this)">

    <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Impedit molestias illo recusandae rem dicta soluta enim optio dolorem, in culpa rerum totam quibusdam ipsa laudantium assumenda? Autem alias magni animi.</p>

    <script>
        
        let Link = {
            setColor: function (color) {
            let links = document.querySelectorAll('a');
            for(var i = 0; i< links.length; i++){
                links[i].style.color = color;
            }
        }}
        
        let Body = {
            setColor: function (color){
                document.querySelector('body').style.color = color; 
            },
            setBackgroundColor: function(color){
                document.querySelector('body').style.backgroundColor = color;
            }
        }

        function toggle(self) {
            if (  self.value === 'night'   ){
                Body.setBackgroundColor('black');
                Body.setColor('white');
                self.value = 'day';
                Link.setColor('orange');
            }
            else {
                Body.setBackgroundColor('white');
                Body.setColor('black');
                self.value = 'night'
                Link.setColor('powderblue');

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

 

 

결과 

 

See the Pen Untitled by zenghyun (@zenghyun) on CodePen.

 

 

'JavaScript > Function implementation' 카테고리의 다른 글

숫자 반환하기  (0) 2022.12.29
정규 표현식으로 특정 문자 검색하기  (1) 2022.12.28
지역 검색 구현하기  (1) 2022.12.24
제곱 함수 구하기  (0) 2022.12.19
day / night mode 구현하기  (1) 2022.12.15
Comments