<!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>storage1.html</title>
    <link href="css/mystyle1.css" rel="stylesheet" />
</head>
<body>
    <div class="container6">
        <textarea rows="5" id="txt1">ttttttttttttttttttt</textarea><br />
        <label for="col1">텍스트 색상 변경</label> 
        <!-- label for ="ID" -> 라벨을 눌러도 ID가 반응함 -->
        <input type="color" id="col1"><br />

        <label for="col2">배경 색상 변경</label>
        <input type="color" id="col2"><br />

        <input type="button" value="색상 저장" id="btn1"/>
        <input type="button" value="초기화" id="btn2"/>
        <input type="button" value="색상 읽기" id="btn3"/>
    </div>
    <script>
        const txt1 = document.getElementById('txt1');
        const col1 = document.getElementById('col1');
        const col2 = document.getElementById('col2');
        const btn1 = document.getElementById('btn1');
        const btn2 = document.getElementById('btn2');
        const btn3 = document.getElementById('btn3');


        col1.addEventListener('change', function() {
            txt1.style.color = col1.value;
        });

        col2.addEventListener('change', function() {
            txt1.style.backgroundColor = col2.value;
        });

        btn1.addEventListener('click', function() {
            const obj = { 
                color : col1.value, 
                bgcolor : col2.value
            };
            console.log(typeof obj); 
            // obj의 type -> object. 저장소에는 string만 들어갈 수 있으니 변경
            // JSON.stringify(@@@) -> object를 string으로 변경
            localStorage.setItem("COLOR", JSON.stringify(obj));
        });
        btn2.addEventListener('click', function() {
            localStorage.removeItem("COLOR"); // 키가 COLOR인 것만 지우기
            // localStorage.clear("COLOR"); 전체 지우기

        });
        btn3.addEventListener('click', function() {
            const str = JSON.parse(localStorage.getItem("COLOR"));
            // str의 타입 -> string. 형식: {"color":"#aeaeae", "bgcolor":"#343434"}
            // 그래서 JSON.parse(@@@)를 사용해 object로 바꿔줌
            console.log(str);
            txt1.style.color = str.color;
            txt1.style.backgroundColor = str.bgcolor;
        });

    </script>
</body>

</html>

0개의 댓글