본문 바로가기

블록체인_9기/💛 JAVASCRIPT

16강_230323_Javascript(getBoundingClientRect, JSON, Storage.clear)

728x90

 

 

 

 


getBoundingClientRect

 

  • 해당 태그의 사각면과 위치 값을 구할 수 있다.
<!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>테스트</title>
    <style>
        div{
            width: 400px;
            height: 600px;

        }
    </style>
</head>
<body>
    <div></div>
</body>
<script>
    let a = document.querySelector('div');
    let b = a.getBoundingClientRect();

    console.log(b);
    /*결과
    DOMRect
        bottom: 607.98828125	//화면 상단부터 태그의 아래 끝 위치의 값
        height: 600		//태그의 높이
        left: 7.98828125	//화면 좌측부터 태그의 왼쪽 끝 위치의 값
        right: 407.98828125	//화면 좌측부터 태그의 오른쪽 끝 위치의 값
        top: 7.98828125		//화면 상단부터 태그의 윗 끝 위치의 값
        width: 400		//태그의 길이
        x: 7.98828125		//화면 좌측부터 태그의 왼쪽 끝 위치의 값
        y: 7.98828125		//화면 상단부터 태그의 윗 끝 위치의 값
    */
</script>
</html>

 

 

 

👩‍🏫예시_스크롤 시 y좌표의 값에 따라 태그가 채워지는 애니메이션

 

<!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>
</head>
<style>
    body{
        padding: 0;
        margin: 0;
    }

    .box{
        position: relative;
        width: 100%;
        height: 500px;
        overflow: hidden;
    }
    
    .box-content{
        position: absolute;
        left: 100%;
        width: 100%;
        height: 100%;
        opacity: 0;
        background-color: aquamarine;
        transition: 1s;
    }

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

    .big-box{
        width: 100%;
        height:120vh;
        background-color: bisque;

    }
</style>
<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>
<script>
    let _boxContents = document.querySelectorAll('.box-content')
    console.log(_boxContents);

    //getBoundingClientRect : 태그의 사각면을 구할 수 있다.
    //반환된 객체의 값이 top left bottom right
    //top
    
    //console.log(_boxContents[0].getBoundingClientRect().bottom);   //브라우저 안에서 영역의 bottom의 y좌표를 알 수 있다. 
    //console.log(_boxContents[0].getBoundingClientRect().left);   //브라우저 안에서 영역의 left의 x좌표를 알 수 있다. 
    console.log(_boxContents[0].getBoundingClientRect().top + window.pageYOffset);   //브라우저 안에서 영역의 top의 y좌표를 알 수 있다. 
    console.log(_boxContents[1].getBoundingClientRect().top + window.pageYOffset);   
    console.log(_boxContents[2].getBoundingClientRect().top + window.pageYOffset);   
    console.log(_boxContents[3].getBoundingClientRect().top + window.pageYOffset);   
    
    let posY = [];
    function init(){
        //초기 세팅
        _boxContents.forEach(function(i){
            //top의 값들을 모두 배열에 담아주고
            //페이지를 새로고침 했을때나 접속했을 때 스크롤이 진행되어있는 값
            //window.pageYOffset
            //페이지 접속했을 때
            posY.push(i.getBoundingClientRect().top + window.pageYOffset);

        })
    }
    init();
    console.log(window.pageYOffset);

    window.onscroll = function(){
        console.log("나 스크롤 되고 있니?")
        //브라우저의 Y스크롤 값이 필요하다.
        //진행된 스크롤 값 (window.scrollY)
        //console.log(window.scrollY);    //스크롤시 맨 윗 영역의 y좌표값을 나타낸다.

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

        let _scroll = window.scrollY + window.innerHeight;      //브라우저 창높이에 도달하면 애니메이션 동작
        
        _boxContents.forEach(function(i,index){
            if(_scroll > posY[index]){
                //if문 사용할 때 중괄호가 없는 경우
                //바로 밑의 코드의 여부만 적용시킬 수 있다.
                if(!i.classList.contains("is-active"))    //! 부정문을 붙어 is-active가 없으면 참
                    i.classList.add("is-active");    //바로 밑줄만 적용
                
            }
            else{
                i.classList.remove("is-active");
            }
        })
    }
    window.onresize = function(){
        console.log(window.innerHeight);
    }

</script>
</html>

 

 

 


JSON

 

  •  Douglas Crockford가 널리 퍼뜨린 Javascript 객체 문법을 따르는 문자 기반의 데이터 포맷
    • JSON 안에는 Javascript의 기본 데이터 타입인 문자열, 숫자, 배열, 불리언 그리고 다른 객체를 포함할 수 다.
  • Javascript와 객체 문법이 아주 유사하지만 꼭 Javascript가 아니더라도 다수의 환경에서 사용가능
  • 문자열 형태로 존재하여 네트워크를 통해 전송할 때 아주 유용하다.
  • 데이터에 엑세스하기 위해서는 JSON객체로 변환될 필요가 있다.
    • Javascript에서는 JSON 전역 객체를 통해 문자열과 JSON 전역 객체를 통해 문자열과 JSON 객체의 상호변환을 지원한다.
    • 문자열에서 JSON객체로 변환하는 것을 파싱(Parsing)이라고 한다.
<!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>테스트</title>
</head>
<body>
</body>
<script>
let superHeroes = {
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}

let a = superHeroes.homeTown
let b = superHeroes['active']

console.log(a);
//결과: Metro City
console.log(b);
//결과: true

// superHeroes객체의 members의 1번 인덱스의 powers의 2번 인덱스 출력
let c = superHeroes['members'][1]['powers'][2]
console.log(c);
//결과: Superhuman reflexes
</script>
</html>

 

  • JSON은 데이터 포맷이므로, 프로퍼티만을 담을 수 있다. 메서드는 담을 수 없다.
  • JSON은 문자열과 프로퍼티의 이름 작성시 큰 따옴표( " " )만을 사용해야 한다. 작은 따옴표( ' ' )는 사용불가!
  • 콤마( , )나 콜론( : )을 잘못 배치하는 사소한 실수로 인해 JSON파일이 잘못되어 작동하지 않을 수 있다.
    • 이와 같은 경우, JSONLint같은 어플리케이션을 사용해 JSON 유효성 검사를 할 수 있다.
  • JSON은 JSON내부에 포함할 수 있는 모든 형태의 데이터 타입을 취할 수 있다. 즉, 배열이나 오브젝트 외에도 단일 문자열이나 숫자또한 유효한 JSON 오브젝트가 된다.
  • 자바스크립트에서 오브젝트 프로퍼티가 따옴표로 묶이지 않을 수도 있는 것과는 달리, JSON에서는 따옴표로 묶인 문자열만이 프로퍼티로 사용될 수 있다.

 

객체와 문자열 사이의 변환

perse( )

  • JSON 문자열을 매개변수로서 수용하고, 일치하는 자바스크립트 객체로서 변환다.

stringify( )

  • 객체를 매개변수로서 수용하고, JSON 문자열 형태로 변환한다.
<!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>테스트</title>
</head>
<body>
</body>
<script>
    //문자열을 객체로 변환
    let _json = '{"key" : "value"}';
    console.log(_json);     
    //결과: {"key" : "value"}

    //JSON객체 안의 parse메소드가 객체로 객체형태의 문자열을 파싱해준다.
    //객체로 변환해준다.
    console.log(JSON.parse(_json));
    /*결과
    {key: 'value'}
    key
    : 
    "value"
    */
    
    //객체를 문자열로 변환
    let obj = {key : 24}; 
    console.log(obj);
    /*결과 
    {key: 24}
    key
    : 
    24
    */

    //객체로 선언된 변수 obj가 문자열로 변환된다.
    console.log(JSON.stringify(obj));  
    //결과: {"key":24}

</script>
</html>

 

 

 


Storage.clear( )

 

  • clear()인터페이스 의 메소드는 주어진 Storage 객체에 저장된 모든 키를 지웁니다
  • 데이터를 지우는 것으로 매개변수와 반환 값이 주어지지 않는다.
//전체 로컬 스토리지 객체의 키를 제거한다.
window.localStorage.clear();

 

 


👩‍🏫예시_input을 이용하여 리스트를 생성하고 요소별 삭제하기

<!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>
</head>
<style>
    li{
        width: 800px;
        height: 80px;
    }

    li > div{
        width: 150px;
        height: 80px;
        border: 1px solid;
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>
<body>
    <label for="">이름</label>
    <input type="text">
    <label for="">나이</label>
    <input type="text">
    <label for="">취미</label>
    <input type="text">
    <label for="">연락처</label>
    <input type="text">

    <button id="addbtn">추가</button>

    <div id="_div">

    </div>
</body>
<script>
    //JSON 문자열을 다뤄보자

    //객체처럼 생긴 문자열
    //데이터를 문자열로 받아서 객체로 변환해서 사용하기 위해
    let _json = '{"key" : "value"}';    //  ' ' 안에서 작성하여 _json의 값을 문자열로 작성하였다.
    console.log(_json);     //결과: {"key" : "value"}

    //JSON객체 안의 parse메소드가 객체로 객체형태의 문자열을 파싱해준다.
    //객체로 변환해준다.
    console.log(JSON.parse(_json));     //변수 _json의 값이 객체로 변환하여 표시된다. 객체로 사용할 수 있는 상태가 된다.
    
    
    //객체를 문자열로 변환
    let obj = {key : 24}; 
    
    console.log(JSON.stringify(obj));   //객체로 선언된 변수 obj가 문자열로 변환된다.

    //window.localStorage.clear();
    function addList(){
        let inputs = document.querySelectorAll("input");

        let value = window.localStorage.getItem("게시판");

        //window.localStorage.clear();      //clear를 동작시키고 주석처리하여 구문을 실행시켜야 한다.
        if(window.localStorage.length == 0 || window.localStorage.getItem('게시판') == "") {
            //${inputs[0].value} 를 " "로 감싸줘야 문자가 정상적으로 입력된다.
            window.localStorage.setItem("게시판",`{"name" : "${inputs[0].value}", "age" : "${inputs[1].value}", "content" : "${inputs[2].value}", "tel" : "${inputs[3].value}"}`);
        }
        else{
            window.localStorage.setItem("게시판",value + "|" +`{"name" : "${inputs[0].value}", "age" : "${inputs[1].value}", "content" : "${inputs[2].value}", "tel" : "${inputs[3].value}"}`);
        }
        
        //문자열을 객체로 변환
        // let _json = JSON.parse(window.localStorage.getItem("게시판"));
        console.log(window.localStorage.getItem("게시판"));
        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");
        let _div4 = document.createElement("div");
        let _div5 = document.createElement("div");
        

        _div1.innerHTML = "이름";
        _div2.innerHTML = "나이";
        _div3.innerHTML = "취미";
        _div4.innerHTML = "전화번호";
        _div5.innerHTML = "삭제";

        _li.style.display = "flex";

        _li.append(_div1,_div2,_div3,_div4,_div5);
        _ul.append(_li);
        if(_json[0] == ""){
            return;
        }
        _json.forEach(function(i,index){
            let _li = document.createElement("li");
            let _div1 = document.createElement("div");
            let _div2 = document.createElement("div");
            let _div3 = document.createElement("div");
            let _div4 = document.createElement("div");
            let _div5 = document.createElement("div");
            let _button = document.createElement("button");
            _button.innerHTML = "삭제";
            _div1.innerHTML = JSON.parse(i).name;
            _div2.innerHTML = JSON.parse(i).age;
            _div3.innerHTML = JSON.parse(i).content;
            _div4.innerHTML = JSON.parse(i).tel;
            _div5.append(_button);

            _button.onclick = function(){
                // splice 첫번째 매개변수 인덱스
                // 두번째 매개변수가 제거할 갯수
                _json.splice(index,1);
                // | 문자로 나눴는데 배열을 문자열로 바꾸면서 
                // 인덱스마다 구분하는 문자를 정해줄수있는 메소드
                window.localStorage.setItem('게시판', _json.join('|'));
                render();
            }

            _li.style.display = "flex";

            _li.append(_div1,_div2,_div3,_div4,_div5);
            _ul.append(_li);
        })
        _div.append(_ul);
    }
    if(window.localStorage.length != 0 && window.localStorage.getItem("게시판") != ""){
        render();
    }

    addbtn.addEventListener("click",addList);       //미리 함수를 만들어 전달할 수도 있다.
</script>
</html>

 

 

728x90