• #2-6 DOM If else Function practice

    2021. 8. 29.

    by. 고구마달랭이

     

    const title = document.querySelector("#title");
    
    const BASE_COLOR = "rgb(52, 73, 94)";
    const OTHER_COLOR = "#7f8c8d";
    
    function handleClick() {
        const currentColor = title.style.color;
        if (currentColor === BASE_COLOR) {
        	title.style.color = OTHER_COLOR;
        } else {
        	title.style.colo = BASE_COLOR;
        }
    }
    
    function init() {
    	title.style.color = BASE_COLOR;
        title.addEventListener("click", handleClick);
    }
    init();

     

    이제 2개의 const 변수를 선언해서 색깔 값을 체크하는데 쓸거예요. 
    어플리케이션을 초기화 하는 init() 이라는 함수도 넣습니다. function init(){
    init(); 함수 호출도 해주고 title도 넣어줍니다.

     

    title.style.color = 'red';
    title.style.color = BASE_COLOR;

    그리고 누군가가 title을 클릭할 때 console.log(title.style.color);를 해줄거예요.

    만약 현재의 색깔이 기본색과 같다면
    if (currentColor === BASE_COLOR) 처음에는 사실이겠죠?
    그리고 누군가 title을 처음으로 클릭 한다면 title.style.color = OTHER_COLOR; 처음엔 currentColor는 BASE_COLOR하고 같아요. 그래서 이 조건문은 참이 됩니다. 그럼 title.style.color는 OTHER_COLOR가 되고요.

    그리고 나서 다음에 title을 클릭하면 currentColor는 BASE_COLOR가 동일하지 않고 그 의미는 이 조건문이 거짓이 된다는 겁니다. 그럼  else { 문을 쓰면 돼요. 이 조건이 사실이 아니면 currentColor가 OTHER_COLOR라는 것입니다.

    댓글