다연이네

[days07] js BOM 본문

Web/JavaScript

[days07] js BOM

 다연  2020. 12. 17. 20:45
반응형

js BOM (Browser Object Mode)
객체(Object) - 브라우저가 제공


1) Window객체
2) Screen 객체
3) Location 객체
4) Navigator 객체
5) History 객체

 

 1) Window 객체 

최상위 객체 -브라우저 창 객체

 

ㄱ. 브라우저 창 
ㄴ. 모든 전역 js객체, 변수, 함수는 자동으로 window 객체의 멤버이다.

<script>	
	var name ;  //	window.name
	function test(){} //	window.test()
	//document 객체도 -> window멤버
	alert(window.document.getElementById("id"));
	window.alert() //alert도 window멤버
    
	//위의 모든 window 는 생략 가능
	
	//브라우저 창의 내부 높이(단위:픽셀)
	//브라우저 창의 내부 너비(단위:픽셀)
	
	//inner~ 도구모음/스크롤바 포함X 너비/높이
	window.innerHeight;
	window.innerWidth;
	
	//IE 8,7,6,5
	document.documentElement.clientHeight;
	document.documentElement.clientWidth;
	//또는
	document.body.clientHeight;
	document.body.clientWidth;
	
	
</script>

 

 

 

 

 

window.open()

window.close()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body > <!-- onload = "window_open()" 준 후 원하는 위치에 여러 창 띄울 수 있음 (팝업 허용) -->
<div id="demo"></div>


<script>
var w =window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

document.getElementById("demo").innerHTML =
	" > 브라우저 inner width : "+w+"inner height : "+h;
</script>

<!-- window.open() / window.close() -->
<button onclick="window_open()">창 열기</button>
<button onclick="window_close()">창 닫기</button>

<script>
var newWin;
function window_open() {
	//[winObj=][window].open(['URL'][,'winTarget'][,'winFeature'])
	newWin = window.open("ex04_03.html"
			,"" //애를 없애버리면 새 탭으로 열린다
			, "width=600, height=500, top=100, left=200");
	//브라우저마다, 버전마다 안먹을 수도 있음
}
function window_close() {
	newWin.close();
}
</script>
</body>
</html>

ex04_03.html

 

window.moveXX() 현재 창 이동 

window.resizeXX() 현재 창 크기 조절

 

XX : To면 절대, By면 상대

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<table border="1" style="width:100%">
   <tr>
      <td>절대위치</td>
      <td onclick="fn_moveto()">moveTo()</td>
   </tr>
   <tr>
      <td>상대위치</td>
      <td onclick="fn_moveby()">moveBy()</td>
   </tr>
   <tr>
      <td>절대크기</td>
      <td onclick="fn_resizeto()">resizeTo</td>
   </tr>
   <tr>
      <td>상대크기</td>
      <td onclick="fn_resizeby()">resizeBy</td>
   </tr>
   <tr>
      <td><button onclick="win_shake();">창 흔들기</button></td>
      <td><button onclick="win_close();">창 닫기</button></td>
   </tr>
</table>

<script>
// window.moveXX() 현재 창 이동
function fn_moveto() {
	window.moveTo(10,10); //절대좌표 위치인 top10, left10 으로 이동
}

function fn_moveby() {
	window.moveBy(10,10); //상대좌표 - 현위치에서 10 10씩 이동
}

	//window.resizeXX() 현재 창 크기 조절
function fn_resizeto() {
		window.resizeTo(300,300); //절대크기 
}

function fn_resizeby() {
		window.resizeBy(10,10); //10 10 씩 커짐
}


function win_close() {
	self.close(); //자기자신창
}
</script>
</body>
</html>

 

1번 버튼을 누르면 새로운 창이 하나 열리고, 2번 버튼을 누르면 그 열린 창이 닫힌다.

 

 


우편번호 검색 창

우편번호 검색 버튼을 누르면 새 창이 뜬다.

검색 버튼을 누르면 밑에 해당하는 주소들이 뜬다. 이 중 한개를 선택하면 해당 창이 닫힌다.

우편번호와 주소가 자동 입력되고 상세주소에 focus()가 맞춰진다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<table border="1" style="width: 500px;margin: 0 auto">
  <tr>
    <td>우편번호</td>
    <td>
    		<!-- zip1, zip2 우편번호 관련 태그는 readonly 속성에 의해 입력 불가 -->
        <input type="text" id="zip1" name="zip1" size="3" readonly="readonly" />-
        <input type="text" id="zip2" name="zip2" size="3" readonly="readonly"/>
        <input type="button" value="우편번호 검색"  onclick="search_zipcode()"/>
    </td>
  </tr>
  <tr>
    <td>주소</td>
    <td><input type="text" id="addr1" name="addr1" style="width:90%" /></td>
  </tr>
  <tr>
    <td>상세주소</td>
    <td><input type="text" id="addr2" name="addr2" style="width:90%" /></td>
  </tr>
</table>

<script>

	var zip; //undefined (undefined, 0, false, null은 모두 false다)
	function search_zipcode() {
		if(!zip){ //창이 안띄워져 있으면 == !undefined 
			
		zip = window.open("ex05_02.html","",
				"width=600, height=300, top=100, left=200");
		zip.default_dong="당산"; //전역변수로 선언해 고정값 넣어둠
		//=> ex05가서 body에 onload=init() 주기
		
		}else{ //만일 떠있는 창이 있으면
			zip.focus();
		}
	}
	
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body onload="init();" onunload="win_unload()"> <!-- onunload: 윈도우가 닫혀도 -->

<table border="1" style="width:100%">
  <tr>
    <td>
        검색할 동 입력 :
        <input type="text" id="dong" name="dong" />
        <input type="button" value="검색"  onclick="search_dong();"/> 
    </td>
  </tr>
  <tr>
     <td>
       <div id="searchResult" class="box" style="visibility: hidden;">
         <a href="javascript:sendAddr('123','451','서울 영등포구 당산 1동')">123-451</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','452','서울 영등포구 당산 2동')">123-452</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','453','서울 영등포구 당산 3동')">123-453</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','454','서울 영등포구 당산 4동')">123-454</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','455','서울 영등포구 당산 5동')">123-455</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','456','서울 영등포구 당산 6동')">123-456</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','457','서울 영등포구 당산 7동')">123-457</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','458','서울 영등포구 당산 8동')">123-458</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','459','서울 영등포구 당산 9동')">123-459</a>서울 영등포구 당산 1동<br>
         <a href="javascript:sendAddr('123','461','서울 영등포구 당산 10동')">123-461</a>서울 영등포구 당산 1동<br>
       </div>
     </td>
  </tr>
  <tr>
    <td>
      <div class="box" style="visibility: hidden;">
         '당산' 검색 결과 10개 검색되었습니다. 
      </div>
    </td>
  </tr>
</table>

<script>
	function init() {
		document.getElementById("dong").value = default_dong; 
	}
	
	function search_dong() {
		//DB 입력받은 동으로 select -> 출력 (원래 해야하는 일인데 우리는 그냥 위에서 고정값 넣어줌)
		//document.getElementById("searchResult").style.visibility="visible";
		var searchList = document.getElementsByClassName("box");
		for (var i = 0; i <searchList.length; i++) {
			searchList[i].style="visible";
		}
	}
	
	function sendAddr(zip1, zip2, addr) {
		//우편번호 검색창을 띄운 부모창?
		opener.document.getElementById("zip1").value = zip1;
		opener.document.getElementById("zip2").value = zip2;
		opener.document.getElementById("addr1").value = addr;
		
		self.close();
		
		opener.document.getElementById("addr2").focus();
	}
	
	function win_unload() {
		opener.zip = null; //null줘야 우편번호 수정할 수 있게 또 열림
	}
</script>
</body>
</html>

 2. screen 객체 

[window.]screen 객체 - 사용자 화면에 대한 정보를 포함하는 브라우저에 내장된 객체 (해상도,크기, ..)

 

<script>
	//screen.width, screen.height
	//screen.availWidth, screen.availHeight --작업표시줄 제외한 화면 너비, 높이
	//screen.colorDepth 화면상의 색상수
	
	var output = "";
	output += screen.width +"/"+ screen.height+"<br>";
	output += screen.availWidth +"/"+ screen.availHeight+"<br>";
	output += screen.colorDepth +"<br>";
	
	$("#demo").html(output);
	
	
	
</script>

 


 3. Location 객체 

1. 현재 페이지의 주소(URL)를 얻기 위해 새로운 페이지로 리다이렉션(redirect)-이동할 수 있다
2. 현재 페이지의 주소(URL)의 정보를 가지고 있는 객체

 

location.href  현재 페이지의 URL을 반환

location.hostname 도메인 명 반환

location.protocol  사용된 웹 프로토콜 반환

location.assign()  새 문서 로드

 

새페이지 로드 (링크마냥)

<script>
	//페이지 이동 (새 페이지 로드) (둘중 아무거나 가능) 차이는 ? 
	function move1() {
		location.href="ex01.html";	 //속성 (대부분 얘 많이 씀(이유는없다))
	}
	
	function move2() {
		location.assign("ex02.html");  //함수
	}
</script>

 

 

<body>
<a href="javascript:history.back()">이전 페이지로 이동</a>
<!-- -2,-3 등 n값이 들어가도 되며, history.back() == history.go(-1)이다.-->
<script>
	var url =  location.href;
	document.write(url+"<br>"); //http://localhost/webPro/javascript/days07/ex07.html
	document.write(location.hostname+"<br>");  //localhost
	document.write(location.protocol+"<br>");  //http:
		//기본 포트 번호인 경우에는 표시하지 않는다 http: 80 	https 443
	document.write(location.port+"<br>");  //포트번호 반환 
</script>

 4. History 객체 

[window.]history - 브라우저의 역사를 갖고 있는 객체

ㄱ. history.back() - 이전 페이지로 이동
ㄴ. history.forward() - 다음 페이지로 이동 (이동할 다음 페이지가 있어야 함)

 

이전 페이지로 이동하기

<body>
<a href="javascript:history.back()">이전 페이지로 이동</a>
<!-- -2,-3 등 n값이 들어가도 되며, history.back() == history.go(-1)이다.-->
</body>

 5. Navigator 객체 

방문자 브라우저 정보를 갖고있는 객체

 

<script>
	document.write(navigator.appName+"<br>"); //Netscape (브라우저의 응용프로그램명)
	document.write(navigator.appCodeName+"<br>"); //Mozilla (브라우저의 응용프로그램 코드명)
	document.write(navigator.product+"<br>"); //Gecko (브라우저가 사용하는 엔진명)
	document.write(navigator.cookieEnabled+"<br>"); //true (브라우저 쿠키 사용 여부)
	document.write(navigator.appVersion+"<br>");  // (브라우저 응용프로그램 버전)
	//5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
	//Chrome/87.0.4280.88 Safari/537.36
	document.write(navigator.javaEnabled+"<br>"); //(자바 사용 여부)
	//function javaEnabled() { [native code] }
	document.write(navigator.platform+"<br>"); //Win32 (브라우저 운영체제)
</script>

 

반응형
Comments