오늘은 저번 객체에 이어서 window용 객체로 시작한다.
window용 객체란?
window객체는 자바스크립트 최상위 객체이며 BOM과 DOM으로 나뉜다.
- BOM(Browser Object Medel) : location 객체(주소창 관리), screen객체(창 과 관련), navigator객체(브라우저와 관련)
- DOM(Document Object Medel) : document 객체
시작하기 전에 window. 이 붙어있는 것들은 모두 생략이 가능하다.
window.open(); 새창 열림
[window.]open(["url", "창 의 특정"])
<button onclick="test1()">네이버</button>
<script>
function test1(){
// window.open()); 새창열림
//window.open(첫번쨰, 두번째 ,세번째);
//첫번째 : 새창에서 열고자하는 url 주소
window.open("http://www.naver.com")
}
</script>
버튼을 누르면 네이버로 이동하게된다.
window객체의 timer관련 메소드
window.setTimeOut
window.setTimeOut(함수, 시간(ms))
<button onclick="test2()">실행</button>
<script>
function test2(){
const myWindow = window.open();
myWindow.alert("ㅋㅋㅋㅋ");
setTimeout(function(){
myWindow.close();
}, 3000) //1s ==1000ms
//3초 후에 페이지 종료
console.log("setTimeout 이전");
setTimeout(function(){
console.log("setTimeout 완료")
})
console.log("setTimeout 이후");
function setTimeOut(callback, time){
//시간지연 true
callback();
}
}
</script>
실행버튼을 누르고 ㅋㅋㅋ 팝업창 확인을 눌러서 없애면 3초후에 종료된다.
window.setInterval
window.setInterval(함수, 시간ms)
<button onclick="test3()">실행</button>
<div id="area1" class="area"></div>
<script>
function test3(){
const area1 = document.getElementById('area1');
let count = 0;
setInterval(function(){
area1.innerHTML = count ++;
//시계만들기
area1.innerHTML = getNowTimeHHMMSS();
}, 1000);
}
하지만 위 시간은 한자리수 1~9가 나오면 00 : 00 : 0 처럼 뭔가 마음이 불편해진다. 이것을 고쳐보자
10보다 작을 때 자리수 앞에 강제로 0을 붙여주면 된다.
function getNowTimeHHMMSS(time){
const now = time ? new Date(time) : new Date();
let hour = now.getHours();
let min = now.getMinutes();
let sec = now.getSeconds();
if(hour < 10){
hour = "0" + hour;
}
if(min < 10){
min = "0" + min;
}
if(sec < 10){
sec = "0" + sec;
}
const str = hour + " : " + min + " : " + sec;
return str;
}
</script>
BOM(Browser Object Model)
location 객체 (브라우저 주소창과 관련)
replace외에는 그냥 사용법이라서 딱히 특이한게 없다.
<button onclick="console.log(location)">실행확인</button>
<a href="http://www.naver.com">네이버로 이동</a>
<button onclick="location.href='http://www.naver.com'">네이버로 이동</button>
<button onclick="location.assign('http://www.google.com')">구글로 이동</button>
<button onclick="location.replace('http://www.google.com')">구글로 이동2</button>
<!-- replace는 뒤로가기를 사용할 수 없도록 ip와 포트이외에 경로를 삭제함-->
<br><br>
<button onclick="location.href = location.href">새로고침</button>
<button onclick="location.reload()">새로고침</button>
<br><br><br>
<h3>screen객체</h3>
<button onclick="console.log(screen)">screen객체 확인</button>
<h3>navigator객체</h3>
<button onclick="console.log(navigator)">navigator객체 확인</button>
<h3>history객체</h3>
<button onclick="console.log(history)">history객체 확인해보기--</button>
DOM에 구성해보기
<h1>DOM 구성하기</h1>
<p>
HTML에 있는 각각의 요소들을 노드(node)라고 함 <br>
>요소노드(Element Node) : 태그 그 자체만을 의미 <br>
>텍스트노드(Text Node) : 태그내에 기록되는 내용 <br><br>
</p>
<button onclick="test4()">Element 직접 생성</button>
<div id="area2"></div>
<script>
function test4(){
//<h3>안녕하세요</h3>
//동적으로 요소를 만드는 방법1. "문자열"
document.getElementById('area2').innerHTML = "<h3>안녕하세요</h3>"
//동적으로 요소를 만드는 방법2. document에서 제공하는 메소드를 통해서 생성;
let h3E1 = document.createElement("h3"); //<h3></h3>
h3E1.innerText = "안녕하세요";
document.getElementById('area2').appendChild(h3E1); //appendChild맨 마지막 자식요소로 추가
}
</script>
Event
이벤트란?
특정 요소객체를 가지고와서 해당 요소의 이벤트 속성에 접근한 후
이벤트 핸들러를 연결하는 방식
이벤트 제거할 수도 있음
이벤트 모델 종류에는 총 3가지가 있다.
- 고전 이벤트 모델
- 인라인 이벤트 모델
- 표준 이벤트 모델
1.고전 이벤트 모델
button id="btn1">실행확인</button>
<button id="btn2">실행확인</button>
<div id="area1" class="area"></div>
<script>
const area1 = document.getElementById("area1");
const btn1 = document.getElementById("btn1");
btn1.onclick = function(){
area1.innerHTML += "btn1이 클릭되었습니다. <br>";
}
document.getElementById("btn2").onclick = function(){
area1.innerHTML += "btn2가 클릭되면서 btn1의 이벤트가 제거됨 <br>";
btn1.onclick = null;
}
</script>
2. 인라인 이벤트 모델
w3c에서 공식적으로 지정한 이벤트 모델
<button id="btn5">실행확인</button>
<script>
const btn5 = document.getElementById("btn5");
//이벤트를 걸고자 하는 요소객체.addEventListener("이벤트명", 이벤트 핸들러);
btn5.addEventListener("click", function(){
alert("표준이벤트 모델 테스트");
});
btn5.addEventListener("mouseenter", function(){
btn5.style.background = "red";
btn5.innerHTML = "클릭!!";
});
btn5.addEventListener("mouseleave", function(){
btn5.style.background = "white";
btn5.innerHTML = "실행확인";
});
</script>
(현재 이벤트가 발생한 요소 객체에 접근하는 방법)
<button id="btn6">기본이벤트 방식</button>
<button id="bun7">표준이벤트 방식</button>
<button onclick="test5(event, this)">인라인 이벤트 방식</button>
<button>인라인 이벤트 방식2</button>
<script>
document.getElementById("btn6").onclick = function(ev){ //이벤트 핸들러
console.log(ev); //이벤트에 관련된 정보가 들어있는 객체를 첫 번째 인자로 넘겨준다.
console.log(window.event);
//현재 이벤트가 발생한 요소
console.log(ev.target);
//이벤트를 호출한 요소
console.log(this);
ev.target.innerHTML = "버튼이 클릭됨";
this.style.color = "red";
}
document.getElementById("btn7").addEventListener("click", function(ev){
console.log(ev.target);
console.log(this);
})
function test5(evnet, _this){
console.log(this);
}
</script>
function안에 있는 ev는 그냥 매개변수 명으로써 전달해주는 인자일 뿐이다. 다른이름을 사용해도 무방하다.
'JavaScript' 카테고리의 다른 글
부트스트랩 사용법 (2) | 2024.03.24 |
---|---|
jQuery에 대하여 (0) | 2024.03.21 |
[3일차] JavaScript의 함수와 객체 (0) | 2024.03.19 |
JavaScript의 변수에 함수 넣기, 자료구조 (0) | 2024.03.18 |
JavaScript에서의 변수와 자료형, camelCase (0) | 2024.03.16 |