Published 2022. 12. 21. 15:34

Window객체는 자바스크립트에서의 최상위 객체이며 크게 BOM과 DOM으로 나뉨

- BOM (Browser Object Model) 
    loacation객체, screen객체, navigator객체, history객체

- DOM (Document Object Model) 
   document 객체

 

- window.onload : 페이지가 로딩됨과 동시에 실행

<script>
        window.onload = function(){
            console.log("문서읽기 완료");
        }
   </script>

 

- window.open("url", "창이름", "창의특성");

 url :  새창에서 열고자하는 url주소
 target(창이름) : 창이름이 같은것이 열려있을 경우 새로이 열리지 않고 이미 열려있는 창에 새로고침됨
 창의 특성 : 새 창의 너비, 높이, 주소창여부, 툴바 여부, 스크롤바 여부 등
                   새로운 창의 특성지정(브라우저마다 적용범위다름)

                   width :창의 너비 / height : 창의 높이 => px  단위 
                   resizable : 창 크기 조절 가능 여부 / location : 주소창 여부
                   menubar :메뉴바 여부 / scollbars : 스크롤바 여부
                   status : 상태표시줄 여부/ toolbar : 도구모음 여부   => yes | no 

<button onclick="test1()">네이버</button>
<script>
    function test1(){  
      /*window.*/open("http://www.naver.com","ㅋㅋ","width=500,height=600, resizable=no,location=no, menubar=no, scrollbars=no,status=no,toolbar=no");  
    }

   </script>

 

window 객체의 timer관련 메소드 

- window.setTimeout(함수, 일정시간ms)
   : 일정시간 후 해당 함수 "단 한번"만 실행

<button onclick="test2()">실행확인</button>

   <script>
    function test2(){
        const newWindow = window.open(); // 새로 열린창의 window객체를 반환 
        newWindow.alert("3초 후에 이 페이지는 종료됩니다."); //새로 열린창 윈도우객체에 알람창 띄우기
        setTimeout(function(){
            newWindow.close();
        },3000);
    }
   </script>

 

- window.setInterval(함수, 일정시간ms) 
  : 지정한 시간 마다 "매번"함수 실행 ->  실시간 검색어나 채팅에 사용됨

  <button onclick="test3();">실행확인</button>
   <div id="area1" class="area"></div>

   <script>
    function test3(){
        const divEl = document.getElementById("area1");
      
        setInterval(function(){
      
            const today = new Date();
            let hour = today.getHours();
            let min = today.getMinutes();
            let sec = today.getSeconds();

            if(hour < 10){ // 한자리 수일 경우 앞에 0붙이기 
                hour = "0" + hour;
            } 
            if(min<10){
                min = "0" + min;
            }
            if(sec<10){
                sec = "0" + sec;
            }

            divEl.innerHTML= hour + " : "+ min + " : "+ sec; 
        }, 1000);
    }
   </script>

 * BOM ( Browser Object Model)

 

location 객체

: 브라우저 주소창(URL)과 관련된 객체로 프로토콜 종류, 호스트이름, 문서위치등의 정보를 가짐 

 

- url 변경하기 (페이지 이동)

1. location.href 

 <button onclick="location.href='http://www.naver.com';">네이버로 이동</button>

 

2. location.assign

  <button onclick="location.assign('http://www.google.com');">구글로 이동</button>

 

3.location.replace -> 뒤로가기 안됨 

<button onclick="location.replace('http://www.google.com')">구글로 이동</button>

 

- 새로고침 버튼 만들기

 1.location href   -> 버튼을 누르면 새로고침되면서 페이지 맨위로 이동됨 

 <button onclick="location.href=location.href;">새로고침</button><br>

2.location.reload -> 현재 보고있는 곳에서 새로고침됨 

<button onclick="location.reload();">새로고침</button>

 

screen객체

 운영체제 화면에 대한 속성값을 가지는 객체

 height / width / availWidth(실제사용가능너비) / availHeight(실제사용가능 높이) / colorDept(사용가능한 색상수) 등

navigator객체

 브라우저에 대한 정보를 가지는 객체

 appName(브라우저명) / platform(사용중인 운영체제)/ language(브라우저언어) 등

 

history객체

 윈도우 열람이력을 최근에 방문한 url배열로 반환 

 


* DOM ( Document Object Model)

HTML에 있는 태그를 객체화 하여 자바스크립트에서 다룰 수 있게 한 것으로 
모든 노드 객체에 접근할 수 있는 요소와 메소드 제공 

노드 : HTML에 있는 태그를 구조화(트리) 하였을때 각각의 태그가 노드 
> 요소노드 (Element Node)  : 태그 그 자체만을 의미
> 텍스트노드 (Text Node) : 태그 내에 기록되는 내용 

텍스트노드가 있는 요소 (시작태그와 종료태그가 쌍으로 이뤄져 있는 요소) : h1, li , p , a ,..
텍스트노드가 없는 요소 (시작태그로만 이뤄져있는 요소) : input, img,...

 

노드 생성과 관련된 메소드

 

텍스트 노드 존재하는 노드생성(시작태그+ 종료태그)

 

- 동적으로 요소만드는 방법

1.  createElement("태그") : ElementNode객체 생성
2.  createTextNode("문구") : TextNode 객체생성
3.  객체명.appendChild(node) : 태그에 자손으로 노드를 추가 

   <button onclick="test4();">노드생성</button>
    <div id="area2"></div>
 <script>
 function test4(){
       
            let elementNode = document.createElement("p");//<p>요소 객체
            let textNode = document.createTextNode("안녕하세요");//안녕하세요 객체

            //두개의 노드를 결합(즉, 요소노드 하위로 텍스트노드 추가)
            elementNode.appendChild(textNode); //<p>안녕하세요</p>

            console.log(elementNode);
            
            document.getElementById("area2").appendChild(elementNode);
        }
    </script>

 

 

텍스트노드가 존재하지 않는 노드 생성 (시작태그만 존재)

1. createElement("태그") :  ElementNode객체 생성
2. 객체에 속성 추가 

<button onclick="test5();">노드생성</button>
    <div id="area3"></div>

    <script>
        function test5(){
            //<img src="이미지주소|파일의경로" width="" height="">
            let imgEl = document.createElement("img"); //<img>

            //속성 추가
            imgEl.src = "https://s.pstatic.net/dthumb.phinf/?src=%22https%3A%2F%2Fdiscovercrop-phinf.pstatic.net%2F%2FMjAyMjEyMTdfMjk4%2FMDAxNjcxMjg3NjM1NzA0.JFYutTcdRB91g7ww43Op1OYMtsIPRfz8pYR4kot4b44g.57W1eNMRerTNJq1ONZi55-qwTuNnGonYj7CVQVy3ghwg.JPEG%2Fimage_750x420.jpg%22&type=nf464_260";
            imgEl.width = "200";
            imgEl.height = "100";

            console.log(imgEl);

            document.getElementById("area3").appendChild(imgEl);
        }

    </script>

 

 

 

노드(요소) 삭제와 관련된 메소드  

지우고자하는 요소객체. remove();

<button onclick="test6();">요소삭제</button>

    <script>
        function test6(){
            document.getElementById("area3").firstChild.remove(); //첫번째 자손 삭제 
        }
    </script>

 

'Front > JavaScript' 카테고리의 다른 글

JavaScript 11. 정규표현식  (0) 2022.12.22
JavaScript 10. 이벤트  (0) 2022.12.21
JavaScript 08. 객체_ 2  (0) 2022.12.20
JavaScript 08. 객체_ 1  (0) 2022.12.20
JavaScript 07. 함수  (0) 2022.12.19
복사했습니다!