[JavaScript] 원하는 컬러로 배경색 변경하기

     

     

    나의 로직

    1) 컬러를 선택하는 input 요소 => input type = "color"

    2) 버튼 클릭시 함수를 호출한다.

    2_2) 이 함수내 에서 컬러 변경이 이루어진다.

    3) 그 값을 배경색으로 변경한다. => value 이용

     

     


     

    모범답안

     

    방법 1) ID로 요소 객체를 가져와서 그 값을 대입하기

    <script>
        function colorChange(){
    
            var area1 = document.getElementById("area1");
            var color = document.getElementById("color");
    
            area1.style.backgroundColor = color.value;
    
        };
    </script>

     

     

    방법 2) 한 코드로 기술하기 

    <script>
        function colorChange(){
    
        document.getElementById("area1").style.backgroundColor = document.getElementById("color").value;
       
       };
    </script>

     


    셀프 피드백

     

     

    • 잘했어요 ! 
    • 기본적인 로직에 접근했다. (input type ="color", onclick = "colorChange();",value등)
    • 논리적으로 생각한 뒤에 코드를 기술했다. 
    • 접근해야하는 요소 객체가 2개 이상이라는 것을 파악했다.

     

    • 아쉬운 점!
    • 변수명을 혼란스럽게 기술했다. 길더라도 명확한 변수명을 제시하자.
    • value 속성을 사용해야하는 건 알았는데, 정확하게 어디에 어떻게 사용해야하는지 몰랐다. 

     


     

    전체 코드

     

    <!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>
            .area{border: 1px;
                background-color: black;
                width:100px;
                height:100px}
        </style>
    </head>
    <body>
        
    <h3>문제1. 색상 선택 후 변경 버튼을 클릭하면 색상이 변경되도록 만들어 보시오</h3>
    
    <div id="area1" class="area"></div>
    
    <input id="color" type="color">
    
    <button onclick="colorChange();">변경</button>
    
    <script>
        function colorChange(){
    
            document.getElementById("area1").style.backgroundColor = document.getElementById("color").value;
    
    
        };
    </script>

     

    성공적으로 변경되는 것을 확인할 수 있다.

     

     

     

    같은 문제를  jQuery로 푸는 방법 ! 

    seongeun-it.tistory.com/114

     

    [jQuery] 사용자에게 입력받은 색상값을 출력하기

    기본적인 문제는 다음과 같다. input type = "color" 2) 버튼 클릭시 함수를 호출한다. 2_2) 이 함수내 에서 컬러 변경이 이루어진다. 3) 그 값을 배경색으로 변경한다. => value 이용 모범답안 " data-og-host="s

    seongeun-it.tistory.com

     

    728x90

    댓글