BOM(Browser Object Model)
- 윈도우에 로드된 문서의 URL, 브라우저가 출력된 스크린 장치, 브라우저의 종류와 기능 등 브라우저와 브라우저가 실행되고 있는 환경을 자바스크립트 코드로 접근하고 제어할 수 있도록 설계된 그룹
- 종류 : window객체는 브라우저가 제어하는 BOM객체의 최상위에 존재
- window
- navigator
- history
- location
- screen
Window
- window객체 : window객체는 열려있는 브라우저 윈도우나 탭 윈도우를 나타내는 객체로 윈도우마다 하나의 window객체가 생성
- window객체가 생성되는 경우
1. 브라우저가 새로운 웹 페이지를 로드할 때 window객체 자동생성
2. <iframe>태그 당 하나의 window 객체 자동생성
3. 자바스크립트 코드로 임의의 window 객체 생성
예시) window.open("웹페이지 URL","window이름"," window속성)
→ 실행되며 새 윈도우(혹은 탭 윈도우)가 열리고 웹 페이지가 출력됨 - window객체의 프로퍼티와 컬렉션
프로퍼티 | 컬렉션 |
window / self | 현재 윈도우 객체에 대한 레퍼런스 |
document | 윈도우에 담긴 document 객체에 대한 레퍼런스 |
name | 윈도우 이름 문자열 |
location | location 객체에 대한 레퍼런스 |
history | history 객체에 대한 레퍼런스 |
locationbar | 위치바 객체에 대한 레퍼런스 |
menubar | 메뉴바 객체에 대한 레퍼런스 |
personalbar | 북마크 툴바 등 사용자 개인의 취향에 따라 기능을 두는 바 |
scrollbars | 스크롤바 객체에 대한 레퍼런스 |
toolbar | 툴바 객체에 대한 레퍼런스 |
status | 상태바에 출력한(출력되는) 문자열 보안상의 이유로 대부분의 브라우저에서 이를 허용하도록 세팅해야 문자열 변경가능 |
closed | 현재 창이 닫혀 보이지 않는 상태면 true |
frames | 윈도우에 존재하는 iframe객체에 대한 컬렉션 |
length | 윈도우에 존재하는 iframe의 갯수 |
top | 윈도우 계층 구조에서 최상위 윈도우 객체에 대한 레퍼런스 |
parent | 현재 윈도우의 부모 윈도우 객체에 대한 레퍼런스 |
navigator | navigator 객체에 대한 레퍼런스 |
outerWidth | 윈도우 전체의 폭 |
outerHeight | 윈도우 전체의 높이 |
screenX | 스크린 상의 윈도우 x좌표 |
screenY | 스크린 상의 윈도우 y좌표 |
pageXOffset | scrollX와 동일하며 현재문서의 스크롤 x값 |
pageYOffset | scrollY와 동일하며 현재문서의 스크롤 y값 |
scrollX | pageXOffset과 동일 현재 문서의 스크롤 x값 |
scrollY | pageYOffset과 동일 현재 문서의 스크롤 y값 |
- window객체의 메소드
메소드 | 의미 |
open() | 새윈도우 열기 |
close() | 윈도우 닫기 |
focus() | 윈도우에 포커스를 주어 키보드 입력을 받을 수 있는 상태로 만듬 |
blur() | 현재 윈도우는 포커스를 잃음 |
getSelection() | 윈도우 내에 선택된 텍스트를 문자열로 리턴 |
stop() | HTML페이지 로딩 중단 브라우저의 stop버튼을 누른것과 동일 |
alert() | 경고 다이얼로그 출력 |
confirm() | 확인 다이얼로그 출력 |
prompt() | 프롬프트(입력) 다이얼로그 출력 |
print() | 현재 페이지를 출력하기 위해 프린트 다이얼로그 출력 |
postMessage() | 다른 윈도우나 워커 태스크로 문자열 데이터 송신 |
setInterval() | 타임아웃 코드가 반복 호출되도록 타이머 가동 |
clearInterval() | setInterval()로 가동시킨 타이머 중단 |
moveBy() | 지정된 픽셀만큼 윈도우 이동 |
moveTo() | 지정된 위치로 윈도우 이동 |
resizeBy() | 지정된 크기만큼 윈도우 크기 조절 |
resizeTo() | 지정된 크기로 윈도우 크기 조절 |
scrollBy() | 주어진 픽셀만큼 상하좌우 스크롤 생성 |
scrollTo() | 특정 좌표로 스크롤 |
- window.open() : 윈도우 열기
형식 : window.open(URL, WindowName, Feature)
- URL : 윈도우에 출력할 웹 페이지 주소 문자열
- WindowName : 새로여는 윈도우의 이름 문자열, 생략가능
- Feature : 윈도우의 모양, 크기 등의 속성들을 표현하는 문자열, 속성들은 빈칸없이 콤마(',')로 분리, 생략가능 - location 객체 : 윈도우에 로드된 웹 페이지의 URL 정보를 나타내는 객체, 윈도우 열릴 때 자동 생성
URL정보는 location 프로퍼티를 통해 알 수 있음
예시)window.location 또는 location
<예시_1>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window close()</title>
<script>
var newWin = null;//새로 연 윈도우
function load(URL) {
newWin = window.open(URL, "myWin", "left=300,top=300,width=500,height=400");
}
function closeNewWindow() {
if (newWin == null || newWin.closed)//윈도우가 열리지 않았거나 닫힌 경우
return; //윈도우가 없는 경우 그냥 리턴
else
newWin.close(); //열어놓은 윈도우 닫기
}
</script>
</head>
<body>
<h3>window의 colse()로 윈도우 닫기</h3>
<hr>
<a href="javascript:load('http://www.disneyworl.com')">새 윈도우 열기(디즈니 월드)
</a><br>
<a href="javascript:window.close()">현재 윈도우 닫기
</a><br>
<a href="javascript:closeNewWindow()">새 윈도우 닫기</a>
</body>
</html>
↓결과
<예시_2>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>event객체 target</title>
<script>
window.onmouseover = function (e) {
if (e.target.tagName.toLowerCase() != "span")
return;
e.target.style.textDecoration = "underline";
}
window.onmouseout = function (e) {
if (e.target.tagName.toLowerCase() != "span")
return;
e.target.style.textDecoration = "none";
}
</script>
</head>
<body>
<h3>span태그에만 onmouseout/onmouseover</h3>
<hr>
<p>
span태그에서만 <span>마우스</span>가 올라갈때
밑줄이 그어지고 <span>마우스</span>가 내려갈때
밑줄이 사라지도록 하는 <span>javascript</span>코드 작성
</p>
</body>
</html>
↓결과
<예시_3>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>random background</title>
<script>
function randomBackground(obj) {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
obj.style.backgroundColor =
"rgb(" + r + ", " + g + ", " + b + ")";
}
</script>
</head>
<body>
<h3>div클릭</h3>
<hr>
<div onclick="randomBackground(this)">div아무곳이나<strong>클릭</strong>하면
배경색이 변경됩니다
</div>
<div onclick="randomBackground(this)">div아무곳이나<strong>클릭</strong>하면
배경색이 변경됩니다
</div>
<div onclick="randomBackground(this)">div아무곳이나<strong>클릭</strong>하면
배경색이 변경됩니다
</div>
<p>
span태그에서만 <span onmouseover="randomBackground(this)">마우스</span>가
올라올 때 배경색이 변경되고 <span onmouseover="randomBackground(this)">마우스</span>가
내려갈땐 배경색이 변경되지 않습니다
</p>
</body>
</html>
↓결과
<예시_4>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>onmouseover, onmouseout</title>
<script>
var text = ["첫번째_1",
"두번째_2",
"세번째_3",
"네번째_4",
"hello word_5"];
var commentDiv;
function init() {
commentDiv = document.getElementById("commentDiv");
var liArray = document.getElementsByTagName("li");
for (i = 0; i < liArray.length; i++) {
liArray[i].addEventListener("mouseover", over, false);
liArray[i].addEventListener("mouseout", hideCommentDiv, false);
}
}
function over(e) {
var n = 0;
switch (e.target.id) {
case "10": n = 0; break;
case "11": n = 1; break;
case "12": n = 2; break;
case "13": n = 3; break;
case "14": n = 4; break;
}
setCommentDiv(text[n], e);
}
function setCommentDiv(comment, e) {
commentDiv.innerHTML = comment;
commentDiv.style.left = e.clientX + "px";
commentDiv.style.top = e.clientY + "px";
commentDiv.style.border = "1px solid yellow";
commentDiv.style.background = "#bb997744";
commentDiv.style.visibility = "visible";
commentDiv.style.width = "200px";
commentDiv.style.height = "80px";
}
function hideCommentDiv() {
commentDiv.style.visibility = "hidden";
}
</script>
</head>
<body onload="init()">
<h3>아이템에 마우스를 올리면 설명 출력</h3>
<hr>
<p>list</p>
<ul>
<li id="10">첫번째</li>
<li id="11">두번째</li>
<li id="12">세번째</li>
<li id="13">네번째</li>
<li id="14">다섯번째</li>
</ul>
<div id="commentDiv" style="position:absolute"></div>
</body>
</html>
- addEventListener("mouseover",over,false)
ture : 이벤트 흐름 중 캡쳐단계에서 실행될 리스너 등록
false : 버블 단계에서 실행될 리스너 등록
→ 생략가능 / defalt : false
캡쳐단계 : window에서 타겟 객체에서 이벤트 객체가 전파되는 과정(위에서 아래로)
버블단계 : 다시 타겟에서 window까지 이벤트가 전파되는 과정(아래에서 위로) - 표준 DOM이벤트에서 정의한 이벤트 흐름
1. 캡쳐링 단계 : 이벤트가 하위 요소로 전파되는 단계
2. 타겟 단계 : 이벤트가 실제 타깃 요소에 전달되는 단계(예_키보드를 입력했을때)
3. 버블링 단계 : 이벤트가 상위 요소로 전파되는 단계
↓결과
<예시_5>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>event 흐름</title>
</head>
<body>
<p style="color : blue">hello <span style="color : red" id="span">world</span>
</p>
<form>
<input type="text" name="ss">
<input type="button" value="test" id="button">
<hr>
</form>
<div id="div" style="color : green"></div>
<script>
var div = document.getElementById("div")//이벤트 메시지 출력 공간
var button = document.getElementById("button");
//body 객체 캡쳐 리스너 등록
document.body.addEventListener("click", capture, true);//캡쳐단계1
//타겟 객체에 버블 리스너 등록
button.addEventListener("click", bubble, false);//버블단계2
//body 객체에 버블 리스너 등록
document.body.addEventListener("click", bubble, false);//버블단계3
function capture(e) { //e는 이벤트 객체
var obj = e.currentTarget; //현재 이벤트를 받은 dom객체
var tagName = obj.tagName; //태그이름
div.innerHTML += "<br>capture단계 : " + tagName + "태그, " + e.type + "이벤트";
}
function bubble(e) {//e는 이벤트 객체
var obj = e.currentTarget; //현재 이벤트를 받은 dom객체
var tagName = obj.tagName; //태그이름
div.innerHTML += "<br>bubble단계 : " + tagName + "태그, " + e.type + "이벤트";
}
</script>
</body>
</html>
↓결과
<예시_6>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>onload로 이미지 크기 출력</title>
<script>
function changeImage() {
var sel = document.getElementById("sel");
var img = document.getElementById("myImg");
img.onload = function () {
//이미지 크기 출력
var mySpan = document.getElementById("mySpan");
mySpan.innerHTML = img.width + "x" + img.height;
}
var index = sel.selectedIndex;//선택된 옵션 인덱스
img.src = sel.options[index].value;//<option>의 value속성
//이미지 로딩시작, 완료 후 onload리스너 호출
}
</script>
</head>
<body onload="changeImage()">
<h3>onload로 이미지 크기 출력</h3>
<hr>
<form>
<select id="sel" onchange="changeImage()">
<option value="../images/apple.png">사과</option>
<option value="../images/banana.png">바나나</option>
<option value="../images/mango.png">망고</option>
</select>
<span id="mySpan">이미지 크기</span>
</form>
<!-- 첫화면 이미지 -->
<p>
<img id="myImg" src="../images/apple.png" alt="apple">
</p>
</body>
</html>
↓결과
<예시_7>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>new Image() 이미지 로딩</title>
<script>
var files = ["../images/penguins.png",
"../images/lighthouse.png",
"../images/Chrysanthemum.png",
"../images/Desert.png",
"../images/Hydrangeas.png",
"../images/Jellyfish.png",
"../images/Koala.png",
"../images/Tulips.png"];
var imgs = new Array();
for (var i = 0; i < files.length; i++) {
imgs[i] = new Image(); //이미지 객체 생성
imgs[i].src = files[i]; //이미지 미리 로딩
}
//다음 이미지 출력,length는 1부터 시작
var next = 1;
function change(img) {
img.src = imgs[next].src; //이미지 변경
next++; //다음 이미지 인덱스
next %= imgs.length; //갯수를 넘으면 처음으로
}
</script>
</head>
<body>
<h3>new Image()로 이미지 로딩</h3>
<hr>
이미지를 클릭하면 다음 이미지를 보여줍니다
<p>
<img style="border: 20px ridge wheat;" src="../images/Penguins.png" alt="animal" width="300" height="300"
onclick="change(this)">
</p>
</body>
</html>
↓결과
<예시_8>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인라인 이벤트 모델</title>
<script>
function btnClick(v) {
alert(v);
}
</script>
</head>
<body>
<input type="button" value="클릭_1" onclick="alert('클릭_1')">
<input type="button" value="클릭_2" onclick="var str='클릭_2'; alert('클릭_2')">
<input type="button" value="클릭_3" onclick="btnClick(value)">
</body>
</html>
↓결과
<예시_9>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>onfocus, onblur</title>
<script>
function checkFiled(obj) {
if (obj.value == "") {
alert("enter name");
obj.focus();
}
</script>
</head>
<body onload="document.getElementById('name').focus();">
<h3>onfocus, onblur</h3>
<hr>
<p>
이름을 입력하지 않고 다른 창으로 이동 할 수 없습니다
</p>
<form>
이름 <input type="text" id="name" onblur="checkFiled(this)">
<p>
학번 <input type="text">
</p>
</form>
</body>
</html>
- onfocus : 포커스가 들어왔을 때
- onblur : 포커스를 잃었을 때
- onchange : select태그에서 선택을 바꾸었을때
- onkeydown : 키보드를 눌렀을때
↓결과
<예시_10>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>onkeydown</title>
<script>
function calculate(e) {
// enter키를 눌렀을때(enter아스키코드 13) 호출됨
if (e.keyCode == 13) {
var exp = document.getElementById("exp");
var result = document.getElementById("result");
result.value = eval(exp.value);
}
}
</script>
</head>
<body>
<h3>계산기 만들기</h3>
<hr>
수식을 입력하고 Enter키를 입력하세요
<p>
<form>
<!-- onkeydown : 키보드를 눌렀을떄 호출되는 함수 -->
식 <input type="text" id="exp" value="" onkeydown="calculate(event)"><br>
결과 <input type="text" id="result">
</form>
</p>
</body>
</html>
↓결과
<예시_11_1>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>라디오 버튼 선택</title>
<script>
function findChecked() {
var found = null;
var kcity = document.getElementsByName('city');
for (var i = 0; i < kcity.length; i++) {
if (kcity[i].checked == true)
found = kcity[i];
}
if (found != null)
alert(found.value + "이 선택");
else
alert("선택된것이 없음");
}
</script>
</head>
<body>
<h3>버튼을 클릭하면 선택된 라디오 버튼의 value값을 출력</h3>
<hr>
<form>
<input type="radio" name="city" value="seoul">서울
<input type="radio" name="city" value="busan">부산
<input type="radio" name="city" value="inchon">인천
<input type="radio" name="city" value="chunchen">춘천
<br>
<input type="button" value="find_checked" onclick="findChecked()">
</form>
</body>
</html>
↓결과
<예시_11_2>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>라디오 버튼 선택</title>
<script>
function findChecked() {
var found = null;
var kcity = document.getElementsByName('city');
var div = document.getElementById('div');
for (var i = 0; i < kcity.length; i++) {
if (kcity[i].checked == true)
found = kcity[i];
}
if (found != null) {
alert(found.value + "이 선택");
div.innerHTML = found.value;
}
else {
alert("선택된것이 없음");
div.innerHTML = "선택된것이 없음"
}
}
</script>
</head>
<body>
<h3>버튼을 클릭하면 선택된 라디오 버튼의 value값을 출력</h3>
<hr>
<form>
<input type="radio" name="city" value="seoul">서울
<input type="radio" name="city" value="busan">부산
<input type="radio" name="city" value="inchon">인천
<input type="radio" name="city" value="chunchen">춘천
<br>
<input type="button" value="find_checked" onclick="findChecked()">
<div id="div" style="color: red;"></div>
</form>
</body>
</html>
↓결과
<예시_12>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>선택된 물품 계산</title>
<script>
var sum = 0;
function calc(cBox) {
if (cBox.checked)
sum += parseInt(cBox.value);
else
sum -= parseInt(cBox.value);
document.getElementById("sumtext").value = sum;
}
</script>
</head>
<body>
<h3>물품을 선택 시 금액 자동계산</h3>
<hr>
<form>
<input type="checkbox" name="hap" value="15000" onclick="calc(this)">모자 1.5만원
<input type="checkbox" name="shose" value="33000" onclick="calc(this)">구두 3.3만원
<input type="checkbox" name="bag1" value="53000" onclick="calc(this)">가방 5.3만원
<input type="checkbox" name="bag2" value="80000" onclick="calc(this)">가방 8만원 <br>
총 금액 : <input type="text" id="sumtext" value="0">
</form>
</body>
</html>
↓결과
<예시_13>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>키 이벤트</title>
<script>
function whatKeyDown(e) {
var str = "";
var div = document.getElementById("div");
div.innerHTML = "";//div객체 내용 초기화
str += "e.key= " + e.key + "<br>";
str += "e.code= " + e.code + "<br>";
div.innerHTML = str;//div 객체 html문자열 출력
}
</script>
</head>
<body>
<h3>키 리스너와 키 이벤트 객체 프로퍼티</h3>
<hr>
텍스트창에 키를 눌러보세요<br>
<!-- onkeypress : <Enter>,<Space>키에 문자키에 대해서만 키가 눌러지는 순간 호출, 아스키값
<!-- onkeydowm : 모든키에 대해서 키가 눌러지는 순간 호출, keycode -->
<input type="text" id="text" onkeypress="whatKeyDown(event)">
<div id="div" style="background-color: skyblue; width:250px; height:70px"></div>
</body>
</html>
키 이벤트 객체의 프로퍼티
- keyCode : 입력된 키의 유니코드 값
- altkey : <Alt>키가 눌러진 상태면 true
- altLeft : 왼쪽 <Alt>키가 눌러진 상태면 true
- ctrlKey : <Ctrl>키가 눌러진 상태면 true
- ctrlLeft : 왼쪽 <Ctrl>키가 눌러진 상태면 true
- shiftKey : <Shift>키가 눌러진 상태면 true
- siftlLeft : 왼쪽 <Shift>키가 눌러진 상태면 true
onreset, onsubmit → <form>태그에 작성
- onreset 리스너는 reset버튼을 클릭해 폼을 초기화 할 때 호출
- onsubmit 리스너는 submit버튼을 클릭해 폼을 서버로 전송 될 때 호출
- onreset 리스너에서 false를 리턴하면 폼이 초기화되지 않음
- onsubmit 리스너에서 false를 리던하면 폼은 서버로 전송되지 않음
↓결과
<예시_14>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>window.location 웹 사이트 접속</title>
<script>
function load() {
var select = document.getElementById('site');
window.location = select.options[select.selectedIndex].value;
};
</script>
</head>
<body>
<h3>window.location 으로 웹 사이트 접속</h3>
<hr>
사이트선택 :
<select id="site">
<option value="http://www.naver.com">네이버</option>
<option value="http://www.google.com">구글</option>
<option value="http://www.microsoft.com">마이크로소프트</option>
</select>
<p>
<button onclick="load()">웹 사이트로 접속</button>
</p>
</body>
</html>
location : 현재 브라우저에 표시된 HTML문서의 주소를 얻거나, 브라우저에서 새 문서를 불러 올 때 사용
window객체의 location프로퍼티와 document객체의 location프로퍼티에 연결되어 있음
→ location객체의 프로퍼티와 메소드를 이용하면 현재 문서의 url 주소를 다양하게 해석 후 처리가능
↓결과
screen
- 브라우저가 실행되는 스크린 장치에 관한 정보를 담고 있는 객체
- 형식 : window.screen 또는 screen
- 프로퍼티
프로퍼티 종류 | 의미 |
availHeight | 작업 표시줄 등을 제외하고 브라우저가 출력가능한 영역의 높이 |
avaiWidth | 작업 표시줄 등을 제외하고 브라우저가 출력가능한 영역의 폭 |
pixelDepth | 한 픽셀의 색을 나타내기 위해 사용되는 비트 수 |
colorDepth | 한 픽셀의 색을 나타내기 위해 사용되는 비트수로서 pixelDepth와 동일(권장) |
height | 스크린의 수직 픽셀 수 |
width | 스크린의 수평 픽셀 수 |
history
- 사용자가 방문한 웹 페이지의 리스트, 히스토리 정보를 담고 있는 객체
- 형식 : window.history 또는 history
예시) history.back(); 또는 history.go(-1); → 이전 페이지로 이동
history.forward(); 또는 history.go(1); → 다음 페이지로 이동 - 프로퍼티
프로퍼티 종류 | 의미 |
length | 히스토리 리스트에 있는 엔트리 수 |
- 메소드
메소드 종류 | 의미 |
back() | 히스토리에 있는 이전 웹 페이지로 이동 브라우저의 <back>버튼과 동일 |
forward() | 히스토리에 있는 다음 웹 페이지로 이동 브라우저의 <forward>버튼과 동일 |
go(n) | 히스토리에서 현재 홈페이지에서 n만큼 상대적인 웹 페이지로 이동 |
'UI > JavaScript' 카테고리의 다른 글
220928_JavaScript_국비_JSON/Canvas (0) | 2022.09.28 |
---|---|
220927_JavaScript_국비_BOM2 (0) | 2022.09.27 |
220923_JavaScript_국비_DOM2 (2) | 2022.09.23 |
220922_JavaScript_국비_Math/ String/ Object/ DOM (1) | 2022.09.22 |
220921_JavaScript_국비_내장함수/ 객체/ Array (2) | 2022.09.21 |