2023.03.23 todolist

이무헌·2023년 7월 19일
0

html,css,js

목록 보기
14/21
post-thumbnail

블로그 게시물 작성 주제에 대한 게시물

주제 1: 세션 저장과 삭제

//setItem 메소드: 첫 매개변수 키 두번째 매개변수 값
sessionStorage.setItem('Token','데이터 내용');//값을 저장
// 세션의 저장된 데이터를 호출
// getItem:세션에 저장된 데이터를 호출 매개변수로는 키값을 전달.

let temp=sessionStorage.getItem('Token');
console.log(temp)

생각보다 간단하다 마치 localstorage를 보는듯 하다.

주제 2: local storage 추가

  1. local storage의 개수
// 로컬 스토리지 길이
console.log(window.localStorage.length);

저장된 로컬 스토레지의 수가 나온다.

  1. local storage 키값 호출
// 로컬 스토리지 키값 호출
window.localStorage.key(0)

key 안은 당연히 인덱스이다. 그 인덱스에 맞는 키값이 나온다!

주제 3:스크롤하면 오른쪽에서 튀어나오는 배경 구현

  1. css
body {
      padding: 0;
      margin: 0;
    }
    .box {
      position: relative;
      width: 100%;
      height: 500px;
      overflow: hidden;
    }
    .big-box{
        height: 100vh;
        width: 100%;
        background-color: aqua;
        opacity: 0;
    }

    .box-content {
      position: absolute;
      left: 100%;
      width: 100%;
      height: 100%;
      opacity: 0;
      background-color: springgreen;
      transition: 1s;
    }

    .is-active {
      left: 0;
      opacity: 1;
    }

2.html

<body>
    <div class="big-box"></div>
    <div class="box">
      <div class="box-content"></div>
    </div>
    <div class="box">
      <div class="box-content"></div>
    </div>
    <div class="box">
      <div class="box-content"></div>
    </div>
    <div class="box">
      <div class="box-content"></div>
    </div>
  </body>

기본적으로 box안에 있는 box-content가 스크롤을 내릴때 오른쪽에서 나오는 걸 구현하는 것이다.

잘 보면 box 안에 있는 box-content의 opacity를 0으로 줬다.

3.js

let _boxcontens = document.querySelectorAll(".box-content");
    console.log(_boxcontens);

    //getBoundingClientRect :태그의 사각면을 구할 수 있다.
    // 반환된 객체의 값이 top left bottom right
    // top
    console.log(
      _boxcontens[0].getBoundingClientRect().top + window.pageYOffset
    );
    console.log(
      _boxcontens[1].getBoundingClientRect().top + window.pageYOffset
    );
    console.log(
      _boxcontens[2].getBoundingClientRect().top + window.pageYOffset
    );
    console.log(
      _boxcontens[3].getBoundingClientRect().top + window.pageYOffset
    );

    let posY = [];
    function init() {
      // 초기세팅
      _boxcontens.forEach((i) => {
        // top의 값들을 모두 배열에 담아주고
        // 페이지를 새로고침했을 때나 접속했을 때 스크롤이 진행되어 있는 값
        //window.pageYOffset
        //
        posY.push(i.getBoundingClientRect().top+window.pageYOffset);
      });
    }

    init();

    window.onscroll = function () {
      // 브라우저의 y 스크롤값
      // 진행된 스크롤 값 window.scrollY
      console.log(window.scrollY);
      // 페이지를 스크롤값 하면서 브라우저의 제일 밑단을 기준으로 바꾸려면?
      // 브라우저의 높이를 더해주면 제일 밑단을 기준으로 변경할 수 있다.
      // 브라우저의 높이는 window.innerHeight
      //   console.log(window.innerHeight + window.scrollY);
      // 브라우저의 bottom을 기준으로 스크롤 값을 구할 수 있당.
      let _scroll = window.scrollY + window.innerHeight;

      _boxcontens.forEach((a,index) => {
        console.log(_scroll);
        console.log(posY[0])

        if (_scroll > posY[index]) {
          if (!a.classList.contains("is-active")) {
            a.classList.add("is-active");
          }
        }else{
            a.classList.remove('is-active');
          }
      });
    };
  • getBoundingClientRect
    해당 객체의 상화좌우 위치를 받아온다
  • pageYOffset()
    으로 현재 위치의 y값을 받아온다.
  • scrollY
    마찬가지로 스크롤 위치를 받아온다. 현재위치이다.
  • let _scroll = window.scrollY + window.innerHeight;
    현재 위치(y값)+현재 창의 높이⇒현재 창의 맨 밑의 y값이된다.
  • 이를 통해 작동원리는 다음과 같다.
    1.각 box의 현재위치를 기준으로 y값을 뽑아온다.
    2.그 다음 box-content 의 현재위치의 y값을 뽑아온다.
    3.사용자가 보는 브라우저의 맨 밑이 box-content의 top보다 커진다면 box-content가 보여져야하므로
    is-active를 통해 opacity와 left를 조정한다.

주제 4:todoList

1.css

.main-container {
        width: 80%;
        margin: auto;
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
      }

      .input-container {
        width: 10%;
        margin: auto;
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
        text-align: center;
      }
      #_div {
        margin: auto;
        width: 41%;
      }
      button {
        margin-top: 40px;
      }
      .todo-list {
      }
      li {
        width: 800px;
        height: 80px;
      }

      li > div {
        width: 150px;
        height: 80px;
        border: 1px solid;
        display: flex;
        justify-content: center;
        align-items: center;
      }

2.html

<body>
    <div class="main-container">
      <div class="input-container">
        <label for="">이름</label>
        <input type="text" />
        <label for="">해야 할 일</label>
        <textarea type="" class="todo"></textarea>

        <label for="">언제?</label>
        <input type="time" />

        <button id="addBtn">추가</button>
      </div>
      <div id="_div"></div>
    </div>
  </body>

3.js

// JSON 문자열을 다뤄보자
    // 객체처럼 생겼음 문자열
    // 데이터를 문자열로 받아서
    // 객체로 변환해서 사용하기 위해
    let _json = '{"key" : "value"}';
    console.log(_json);
    // JSON객체 안의 parse메소드가 객체로 객체형태의 문자열을 파싱해준다.
    // 객체로 변환해준다.
    console.log(JSON.parse(_json));
    let obj = { key: 24 };
    // 객체를 문자열로 변환
    // stringify : 객체를 문자열로 변환
    console.log(JSON.stringify(obj));

    function addList() {
      let name = document.querySelectorAll("input")[0].value;
      let todoContent = document.querySelector("textarea").value;
      let time = document.querySelectorAll("input")[1].value;
      let value = window.localStorage.getItem("게시판");
      // window.localStorage.clear();
      if (window.localStorage.length == 0) {
        window.localStorage.setItem(
          "게시판",
          `{"name":"${name}","todoContent":"${todoContent}","time":"${time}"}`
        );
      } else {
        window.localStorage.setItem(
          "게시판",
          value +
            "|" +
            `{"name":"${name}","todoContent":"${todoContent}","time":"${time}"}`
        );
      }
      console.log(window.localStorage.getItem("게시판"));
      // 문자열을 객체로 변환
      // let _json = JSON.parse(window.localStorage.getItem("게시판"));
      // console.log(_json);
      render();
    }

    function render() {
      let _json = window.localStorage.getItem("게시판");
      // 문자열에서 "|" 문자열마다 잘라서 배열로 변경
      _json = _json.split("|");
      console.log(_json);
      _div.innerHTML = "";
      let _ul = document.createElement("ul");
      let _li = document.createElement("li");
      let _div1 = document.createElement("div");
      let _div2 = document.createElement("div");
      let _div3 = document.createElement("div");
      _div1.innerHTML = "이름";
      _div2.innerHTML = "할일";
      _div3.innerHTML = "언제?";
      _li.style.display = "flex";
      _li.append(_div1, _div2, _div3);
      _ul.append(_li);
      _json.forEach(function (i) {
        let _li = document.createElement("li");
        let _div1 = document.createElement("div");
        let _div2 = document.createElement("div");
        let _div3 = document.createElement("div");
        _div1.innerHTML = JSON.parse(i).name;
        _div2.innerHTML = JSON.parse(i).todoContent;
        _div3.innerHTML = JSON.parse(i).time;
        _li.style.display = "flex";
        _li.append(_div1, _div2, _div3);
        _ul.append(_li);
      });
      _div.append(_ul);
    }

    addBtn.addEventListener("click", addList);
  • JSON.parse()
    json⇒object 형으로 변환해준다. 당연히 json구조의 데이터를 넣어야한다.
  • JSON.stringify()
    object⇒json 형으로 변환해준다.
  • localstorage에 json형태를 저장할 때 백틱(``)안에 변수를 쓸 때 “${}”로 묶어주자 그래야 json 형태를 맞춰줄 수 있다.
  window.localStorage.setItem(
          "게시판",
          value +
            "|" +
            `{"name":"${name}","todoContent":"${todoContent}","time":"${time}"}`
        );

기존에 있던 value(게시판)에 | 로 구분짓고 새로운 데이터를 넣는다.

 _json = _json.split("|");

그 후 split으로 데이터를 나눠준 것이다.

_div.innerHTML = "";

_div안의 데이터는 localstorage에서 불러온 데이터를 append를 해준 것이기 때문에 초기화를 하지 않으면 계속 불어나간다. 주의하자

결론

이번에는 많이 해맸다. if문도 제대로 주지 못했고 json 형식을 다룰 때 parse를 제대로 해주지 못 했기 때문이다. 같은 오류가 나옴에도 해결방법이 다르다는 점이 여전히 무섭지만 해결했을 때의 짜릿함은 배가된다.
앞으로 json을 많이 다루게 될 것 이므로 꾸준히 연습하자

profile
개발당시에 직면한 이슈를 정리하는 곳

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

이런 정보를 찾고 있었습니다, 감사합니다.

답글 달기