기록

*62일차 본문

학원/강의

*62일차

pringspring 2022. 4. 25. 18:57

@Window

 

  • 웹페이지의 모든 자원을 관리하는 최상위 객체
  • window, this, globalThis 키워드를 통해 접근이 가능하다.
  • BOM Browser Object Model(navigator, location, history, screen, XMLHttpRequest, frames...)
  • DOM Document Object Model(document)
  • javascript (Object, Array, String, ...)

 

*open

  • 새로운 탭 또는 팝업창을 여는 메소드
  • open(주소,윈도우명,스펙) : 새 윈도우 객체
  • 윈도우명 : 브라우저의 탭들을 관리하는 이름
  • 기존에 열린 탭중에 해당이름이 존재하면 그탭에 open, 존재하지 않으면 새로 생성
  • _self 현재탭에 해당페이지를 open
  let newWindow;
  const test1 = () => {
    // const newWindow = open("index.html", "_self", "");
    newWindow = open("index.html", "popup", "width=500, height=300, top=300, left=200");
    console.log(newWindow);

    setTimeout(() => {
      newWindow.alert("안녕!!!!");
    }, 3000);
  };
  
    const test2 = () => {
    newWindow.close();
  };

 

*Timer API

  • setTimeout(callbackFunction, millis):timeoutId
  • clearTimeout(timeoutId)
let timeoutId;
  const test3 = () => {
    timeoutId = setTimeout(() => {
      alert("Foooooooooooooooooooooooooo!!!");
    }, 3000);
    console.log("timeoutId : ", timeoutId);
  }
  const test4 = () => {
    clearTimeout(timeoutId);
    console.log(`${timeoutId}번 타이머 취소`);
  };

 

ex)실습문제 :  타이머 생성폼

<fieldset>
    <legend>타이머 폼</legend>
    <input type="text" id="message" placeholder="타이머 메세지를 작성하세요...">
    <br>
    <input type="number" id="sec" min="0" step="10" placeholder="타이머 초를 작성하세요...">
    <br>
    <input type="button" value="타이머 생성" onclick="test5();">
    <input type="button" value="타이머 취소" onclick="test6();">
  </fieldset>
  <script>
  /**
   * @실습문제 : 타이머 생성폼
   */
  let userTimeoutId;
  const test5 = () => {
    if(!message.value || !sec.value) 
      return;

    const _message = message.value;
    userTimeoutId = setTimeout(() => {
      alert(_message);
    }, sec.value * 1000);

    alert(`${sec.value}초후 타이머가 생성되었습니다.`);
    message.value = '';
    sec.value = '';
  };
  const test6 = () => {
    clearTimeout(userTimeoutId);
    alert('타이머가 취소 되었습니다.');
  };

 

******

  • setInterval(callbackFunction, millis)
  • millis초 이후부터 millis초간격으로 callbackFunction을 호출
let intervalId;
  const test7 = () => {
    let initNum = 10;

    intervalId = setInterval(() => {
      counter.innerHTML = --initNum;

      if(initNum === 0){
        clearInterval(intervalId);
      }
    }, 1000);
    console.log('intervalId : ', intervalId);
  };

  const test8 = () => {
    clearInterval(intervalId);
    console.log(`${intervalId} 인터벌 중지`);
  };

 

 

*페이지로딩이 끝나면 시계 작동시키기

  function displayClock(date){
    const f = function(n){
      return (n < 10) ? "0" + n : n;
    };

    const yyyy = date.getFullYear();
    const MM = f(date.getMonth() + 1);
    const dd = f(date.getDate());
    const hh = f(date.getHours());
    const mm = f(date.getMinutes());
    const ss = f(date.getSeconds());

    const str = `${yyyy}/${MM}/${dd} ${hh}:${mm}:${ss}`;
    clock.innerHTML = str;

  }

  // displayClock(new Date()); // #clock이 DOM 등록전이라 찾을 수 없어 오류!!

  const init = () => {
    displayClock(new Date()); // #clock이 DOM등록 완료후이므로 정상작동!

    // setInterval(() => {
    //   displayClock(new Date());
    // }, 1000);
  };
  </script>
  <h3 id="clock"></h3>

 

@BOM

 

*navigator

  • 브라우저에 대한 정보
  const test1 = () => {
    console.log(window.navigator);
    console.log('userAgent : ', navigator.userAgent); 
    // chrome : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36
    // firefox : Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0
    // safari : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15"
  };

 

*location

  • 현재 접속한 페이지 주소관련 정보
const test2 = () => {
    console.log(location);
    const {protocol, hostname, port, pathname, search, hash} = location;
    console.log(protocol, hostname, port, pathname, search, hash);
    // http: 
    // 192.168.10.6 
    // 5500 
    // /03_javascript/17_BOM.html 
    // ?q=hello&type=sss 
    // #abcde
  }
  
  const test3 = () => location.href = "https://www.naver.com";
  const test4 = () => location.reload();
  • location.href = 페이지 이동

 

*history

  • 브라우저 방문기록 정보
  const test5 = () => {
    console.log(history);
  };

*go

  1. go(0) : 새로고침
  2. go(1) : 앞으로가기
  3. go(-1) : 뒤로가기
  const test6 = () => {
    // history.go(0);
    // history.go(1);
    history.go(-1);
  };

*screen

  • 모니터(hw)에 대한 정보를 가진 객체
  const test7 = () => {
    console.log(screen);

    const screenWidth = screen.availWidth;
    const screenHeight = screen.availHeight;
    const popupWidth = 300;
    const popupHeight = 300;
    const left = screen.availLeft + (screenWidth - popupWidth) / 2;
    const top = screen.availTop + (screenHeight - popupHeight) / 2;

    open("", "popup", `width=${popupWidth}, height=${popupHeight}, left=${left}, top=${top}`);

  };

 


 

@DOM

  • Document Object Model
  • 브라우져가 문서를 해석해서 document객체 하위에 계층구조로 태그객체를 관리
  • document.getElementsByXXX, document.querySelector 메소드는 document하위에서 태그객체 찾는 메소드

 

*DOM에 등록된 태그객체

  • Node객체로 관리가 된다
  • 모든 document하위의 객체는 Node객체를 상속한다
  • textNode,commentNode, span, div, p, ....
  const test1 = () => {
    console.log(sample);
    console.dir(sample);
  };

 

*textNode가 있는 태그객체(Element)

  • <h2>여보세요~ 봄이왔어요! </h2>
  const test2 = () => {
    const h2 = document.createElement('h2');
    const text = document.createTextNode('여보세요~ 봄이 왔어요!');
    h2.appendChild(text); // 자식 Node추가시
    target.append(h2); // 자식 Element추가 DOM에 등록

    // target.innerHTML = '<h2>여보세요~ 봄이 왔어요!</h2>';
  };

 

*이미지 태그객체 추가

  const test3 = () => {
    // const img = document.createElement('img');
    // img.src = '../sample/image/flower1.PNG';
    // img.style = 'width: 200px;';
    // target.append(img);

    target.innerHTML = '<img src="../sample/image/flower1.PNG" style="width:200px"/>'
  };

 

 

*자식요소 제거

  const test4 = () => {
    console.log(foo.childNodes); // 텍스트노드 포함 자식요소 반환
    console.log(foo.children); // 텍스트노드 없이 자식태그요소만 반환

    console.log(foo.firstChild); // 텍스트노드 포함 첫번째 자식요소
    console.log(foo.firstElementChild); // 첫번째 자식태그요소 제거
    
    // foo.removeChild(foo.firstElementChild); // p태그 제거

    while(foo.firstElementChild)
      foo.removeChild(foo.firstElementChild);
  };

 

*태그객체 자신을 제거

  const test5 = () => {
    foo3.remove();
  }

 

*Traversing

  • 하나의 dom객체로부터 다른 dom객체를 조회하는 방법
  • -부모/형제/자식
  • Node(텍스트노드포함) | Element(태그객체만 대상)
  const test6 = () => {
    const src = document.querySelector("div.wrapper");
    let dest;
    // dest = src.firstChild; // #text
    // dest = dest.nextSibling.nextSibling.nextSibling; // p#p1 - #text - p#p2
    
    dest = src.lastChild; // #text
    dest = dest.previousSibling; // p#p5
    dest = dest.parentNode; // 부모Node(태그객체) div.wrapper
    
    console.log(dest);
    dest.style.color = 'deeppink';
  };
  const test7 = () => {
    const src = document.querySelector("div.wrapper");
    // let dest = src.firstElementChild; // p#p1
    // dest = dest.nextElementSibling; // p#p2

    let dest = src.lastElementChild; // p#p5
    dest = dest.previousElementSibling; // p#p4
    dest = dest.parentElement; // 부모 Element div.wrapper (parentNode와 늘 동일하다.)

    console.log(dest);
    dest.style.color = 'springgreen';
  };

 

ex)@실습문제 - 자식요소의 TextNode변경

  const test8 = () => {
    const src = document.querySelector("div.wrapper");
    // console.log(src.childNodes);
    console.log(src.children);
    // const arr = Array.from(src.children);
    const arr = [...src.children]; // 전개연산자
    console.log(arr);
    arr.forEach((child, index) => {
      console.log(index, child);
      const text = document.createTextNode(`DOM${index + 1}`);
      // child.removeChild(child.firstChild);
      // child.appendChild(text);

      // replaceChild(newNode, oldNode);
      child.replaceChild(text, child.firstChild);
    });

'학원 > 강의' 카테고리의 다른 글

*64일차 (정규표현식2)  (0) 2022.04.27
*63일차 (Event / 정규표현식)  (0) 2022.04.26
*61일차 - ncs테스트 (UI 디자인)  (0) 2022.04.22
*61일차 - ncs테스트 (UI 디자인)  (0) 2022.04.22
*60일 (상속)  (0) 2022.04.21