728x90
반응형
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <textarea name="txt" id="txt" cols="30" rows="20"></textarea><br/>
    <label for="text-color">글자색 변경</label>
    <input type="color" id="text-color" value="#FFF"><br />

    <label for="bg-color">배경색 변경</label>
    <input type="color" id="bg-color" value="#FFF"><br />

    <button id="set-color">설정 저장하기</button>
    <button id="get-color">설정 불러오기</button>
    <button id="clear">설정 초기화</button>
</body>
</html>



    <script>

        const textArea = document.getElementById('txt');
        const textColor = document.getElementById('text-color');
        const bgColor = document.getElementById('bg-color');
        const setBtn = document.getElementById('set-color');
        const getBtn = document.getElementById('get-color');
        const clearBtn = document.getElementById('clear');


        // 글자색 변경 부분이 색이 ㅂ녀경되었다면
        textColor.onchange = () => {
            // 텍스트 에리아의 색을 변경
            textArea.style.color = textColor.value;
        };
        // 배경색 변경 부분의 색이 변경되었다면
        bgColor.onchange = () => {
            // 텍스트 에리어의 배경을 변경
            textArea.style.backgroundColor = bgColor.value;
        };

        setBtn.onclick= () => {
            // color 값들을 모두 받아서 객체 형태로 저장함
            const colorObj = {txtColor:textColor.value, bgColor:bgColor.value};
            const jsonObj = JSON.stringify(colorObj);
            console.log(jsonObj);
            // 로컬스토리지에 현재 textColor의 값을 'txtColor' key 이름으로 저장함
            localStorage.setItem("textAreaColor", jsonObj);
            alert('설정을 저장했습니다!');

        }
        getBtn.onclick= () => {
            alert('설정을 불러왔습니다!');
            const textAreaColor = JSON.parse(localStorage.getItem('textAreaColor'));
            // 텍스트 에리어 값을 변경
            textArea.style.color = textAreaColor.txtColor;
            textArea.style.backgroundColor = textAreaColor.bgColor;
            // 색상 input값을 변경
            textColor.value = textAreaColor.txtColor;
            bgColor.value = textAreaColor.bgColor;
        }

        clearBtn.onclick= () => {
            let length = localStorage.length;
            while(length > 0){
                localStorage.removeItem(localStorage.key(0));
                length--;
            }
            alert('설정 정보를 삭제하였습니다.');
        }




    </script>

실행 창

728x90
반응형

+ Recent posts

">