[ JavaScript ] style 제어하기

2024. 5. 4. 11:22· FRONT-END/└ JS

환경 : Visual Studio Code

 

 

- 글자의 색상 및 테두리 색상을 바꿔보며 style 제어를 이해해보자 

 

실행결과 (콘솔을 보면 바뀌는 부분의 코드를 알 수 있다)

 

[ 주요 코드 ]

    - 단순히 색상이 변하도록 구현해보기

    <script type="text/javascript">
        
        function changeRed(){
            var target = document.querySelector(".title");
            target.style = "color:red";
        }

        function changeOrange(){
            var target = document.querySelector(".title");
            target.style = "color:orange";
        }

        function changeBlue(){
            var target = document.querySelector(".title");
            target.style = "color:blue";
        }

    </script>

     (+) target 변수에 대한 스타일을 지정한다. (이렇게 사용하게 되는 경우 인라인 태그 전체 덮어쓰기가 되는 것이다. )

                                                                                                                          └ 단점 : 이후 코드의 확장성이 좋지 않음

 

    - 단점 개선 (속성명까지 지정해주기)

    <script type="text/javascript">
        
        function changeRed(){
            var target = document.querySelector(".title");
            //target.style = "color:red";//인라인 style 전체를 덮어쓴다
            target.style.color = "red";//style의 특정 속성을 덮어쓴다 
        }

        function changeOrange(){
            var target = document.querySelector(".title");
            // target.style = "color:orange";//인라인 style 전체를 덮어쓴다
            target.style.color = "orange";
        }

        function changeBlue(){
            var target = document.querySelector(".title");
            // target.style = "color:blue";//인라인 style 전체를 덮어쓴다
            target.style.color = "blue";
        }

    </script>

     (+) target.style.color 까지 지정해주어 style의 특정 속성을 덮어쓰게 해준다. 

                                                                      └ 해당 속성만 덮어씌워짐

 

 

    - 위의 코드 차이를 느낄 수 있는 예시 - 테두리 효과를 주었을 때

    <script type="text/javascript">
        
        function changeRed(){
            var target = document.querySelector(".title");
            //target.style = "color:red";//인라인 style 전체를 덮어쓴다
            target.style.color = "red";//style의 특정 속성을 덮어쓴다 
        }

        function borderRed(){
            var target = document.querySelector(".title");
            //target.style = "border:1px solid red";//인라인 style 전체를 덮어쓴다
            target.style.border = "1px solid red";
        }

    </script>

    (+) 만약 인라인 스타일 전체를 덮어쓰는 경우(첫 번째 코드 사용 시) 여러 버튼을 번갈아 눌렀을 때 제대로 적용되지 않는다. (글씨색 변경 + 테두리 변경이 동시에 이루어지지 않음)

    (+) 만약 style 태그의 특정 속성을 덮어쓰게 코딩하는 경우, 각각의 함수 기능이 올바르게 작동한다. (글씨색 변경 + 테두리 변경이 동시에 이루어짐)


[ 전체 코드 ]

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript 예제</title>

    <!-- 구글 폰트 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100..900&display=swap" rel="stylesheet">
     
    <!-- 내가 구현할 스타일 -->
    <link rel="stylesheet" type="text/css" href="../css/commons.css">
    <link rel="stylesheet" type="text/css" href="../css/test.css">
    
    <!-- font awesome 아이콘 CDN -->
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <style>

    </style>

    <!-- javascript를 의도적으로 head 자리에 배치해서 가장 먼저 실행되도록 구현 -->
    <script type="text/javascript">
        
        function changeRed(){
            var target = document.querySelector(".title");
            //target.style = "color:red";//인라인 style 전체를 덮어쓴다
            target.style.color = "red";//style의 특정 속성을 덮어쓴다 
        }

        function changeOrange(){
            var target = document.querySelector(".title");
            // target.style = "color:orange";//인라인 style 전체를 덮어쓴다
            target.style.color = "orange";
        }

        function changeBlue(){
            var target = document.querySelector(".title");
            // target.style = "color:blue";//인라인 style 전체를 덮어쓴다
            target.style.color = "blue";
        }

        function borderRed(){
            var target = document.querySelector(".title");
            //target.style = "border:1px solid red";//인라인 style 전체를 덮어쓴다
            target.style.border = "1px solid red";
        }

        function borderOrange(){
            var target = document.querySelector(".title");
            target.style.border = "1px solid orange";
        }

        function borderBlue() {
            var target = document.querySelector(".title");
            target.style.border = "1px solid blue";
        }

    </script>
</head>
<body>


    <div class="container w-500">
        <div class="cell center">
            <h1 class="title">자바스크립트로 style 제어하기</h1>
        </div>
        <div class="cell">
            <button class="btn" onclick="changeRed();">빨강</button>
            <button class="btn" onclick="changeOrange();">주황</button>
            <button class="btn" onclick="changeBlue();">파랑</button>
        </div>
        <div class="cell">
            <button class="btn" onclick="borderRed();">빨강테두리</button>
            <button class="btn" onclick="borderOrange();">주황테두리</button>
            <button class="btn" onclick="borderBlue();">파랑테두리</button>
        </div>
    </div>

   

</body>
</html>

 

 

 

 

 

 

 

개인 공부 기록용입니다:)

 

728x90