본문 바로가기

Programming/국비학원

220705 - 자바스크립트 - 객체, BOM

  • string 내장객체

자바스크립트 => string = 객체

 

 

    <script>
        var str="대한민국"
        //var str=new String("대한민국");
        alert(str[0]);  //대
    </script>

 

 

  • 메소드

        var str="computer";
        var ch=str.charAt(2);  //2번째 문자


        var str1="hello thank you good luck to you";
        var pos1=str1.indexOf("you");  //문자의 위치 (찾는 문자열 X = -1) //12
        var pos2=str1.indexOf("you",16)//인덱스 16 이후의 문자열 인덱스값 //29
        var pos3=str1.indexOf("thank",16); //-1 (값이 없음)


        var pos4=str1.lastIndexOf("you"); //뒤에서부터 탐색 //29
        var pos5=str1.lastIndexOf("you",25)//25번째까지만 검색 //12

        var str2=str1.match("you"); //문자열 탐색 후 존재하면 해당 문자열 반환 //you


        var str3="지금은 html 공부중";
        var str4=str3.replace("html","javascript");
        var pos6=str1.search("you"); //첫 문자열 찾아 인덱스번호 반환 //12

 

 

  • 메소드2

        var str1="hello javascript";
        var str2=str1.slice(3,7);  //인덱스 3~6 //lo j
        var str3=str1.slice(3,-3);  
        //인덱스3 ~ (맨뒤 기준)인덱스3까지 //lo javascr

        var str4=str1.substring(3,7); //인덱스 3~6  //lo j
        var str5=str1.substring(5)//인덱스 5~끝
        //var str6=str1.substring(3,-3); //사용 X (음수=>0으로 인식) //hel

        var str6=str1.substr(3,2) //(인덱스 값, 개수)  //lo

        var str7="html*css*javascript";
        var arr=str7.split("*");  //지정한 문자 기준으로 나눠 각 배열에 저장
        alert(arr);  //html,css,javascript
        alert(arr[0]); //html

        var alpha="HTML";
        alert(alpha.toLowerCase()); //전체 소문자화
        //cf. toUpperCase

        var na="자바 웹개발자반";
        var cname=na.concat(" 파이팅"); //문자열 결합
        alert(cname);  //자바 웹개발자반 파이팅

        var asc="ABC";
        alert(asc.charCodeAt(0)); //인덱스 0의 문자에 대응하는 aschii 코드 반환 //65

        alert(String.fromCharCode(65)); //해당 아스키코드에 대응하는 문자 반환

        var h=" hello ";
        alert(h.trim());

 

 

  • 문제 : 전화번호 마지막 네자리 **** 변환

        var tel=prompt("전화번호를 알려주세요","010-0000-0000");
        var result= tel.substring(0,tel.length-4)+"****";
        document.write(result);

 

 

  • 문제 : 이메일 주소에 @, 배열 미포함 시 오류 알림

        var email=prompt("이메일 주소는?"); 
        var arrUrl=[".co.kr",".net",".com",".or.kr",".go.kr"];
        var check1=false;  //@ 검사
        var check2=false;  //url 검사
        
        if(email.indexOf("@")>0){
            check1=true;
        }

        for (var i=0;i<arrUrl.length;i++){
            if (email.indexOf(arrUrl[i])>0){
                check2=true;
                break;
            }
        }

        if (check1&&check2){
            alert("주소가 "+email+"이군요");
        } else {
            alert("이메일 형식이 잘못되었습니다.");
        }

 

 

 

BOM(Browser Object Model) 

: 브라우저 객체 모델

 

 

  • 객체

window : 브라우저 창
location : 주소 창
navigator : 브라우저 정보
history : 방문 기록 저장
screen : 현재 사용 중인 화면 정보 (디스플레이)
document : 웹 문서 (html 문서) 정보 ===> DOM(Document Object Model)

 

 

  • window
  • open 메소드 : 창 열기

    <script>
        //window 객체
        window.open("http://www.kbs.co.kr","kbs","width=500, height=500");
    </script>

 

 

  • moveTo(x,y) : 창 위치를 절대적으로 이동

    <script>
        var child=window.open("","","width=600, height=300"); //blank창
        if (child){
            child.moveTo(100,100); //4사분면 
            child.document.write("<h2>공지사항</h2>");
            child.document.write("<p>내일부터 문서 객체 모델(DOM)을 시작</p>");
            child.document.write("<p>내일부터 개인 홈페이지 교습을 시작</p>");
        }else{  //창 뜨지 않을 때
            alert("팝업 차단을 해지해주세요");
        }
    </script>

 

 

  • moveBy(x,y) : 창 위치를 상대적으로 이동

    <script>
        var child=window.open("","","width=600, height=300"); //blank창
        setInterval(function(){
            child.moveBy(10,10);
        },1000); //1초마다 x, y 좌표 10씩 이동  
        if (child){
            child.document.write("<h2>공지사항</h2>");
            child.document.write("<p>내일부터 문서 객체 모델(DOM)을 시작</p>");
            child.document.write("<p>내일부터 개인 홈페이지 교습을 시작</p>");
        }else{ 
            alert("팝업 차단을 해지해주세요");
        }
    </script>

 

 

  • resizeTo(x,y) / resizeBy(x,y) : 창 크기 절대적/상대적으로 지정

    <script>
        var child=window.open("","","width=600, height=300"); //blank창
        var width=screen.width;
        var height=screen.height;
        setInterval(function(){
            child.moveBy(10,10); 
            child.resizeBy(-20,-20); //점점 크기 감소
        },1000); //1초마다 x, y 좌표 10씩 이동
        if (child){
            child.moveTo(0,0);
            child.resizeTo(width, height); //절대적 창 크기
            child.document.write("<h2>공지사항</h2>");
            child.document.write("<p>내일부터 문서 객체 모델(DOM)을 시작</p>");
            child.document.write("<p>내일부터 개인 홈페이지 교습을 시작</p>");
        }else{  //창 뜨지 않을 때
            alert("팝업 차단을 해지해주세요");
        }
    </script>

 

 

  • location
  • href, assign, replace : 새로운 페이지로 이동

    <script>
        setTimeout(function(){
            location.href="http://www.kbs.co.kr";  

            location.assign("http://www.kbs.co.kr");  //href보다 다소 느리지만 안전

            location.replace("http://www.kbs.co.kr");  //이동 전 페이지가 history에 남지 X

        }, 5000);
    </script>

 

 

  • 새로고침 구현

    <script>
        setInterval(function(){
            //location=location; //아래 코드 href 생략 가능
            //location.href=location.href; 
            //location.assign(location);
            //location.replace(location);
            location.reload();
        },3000);
    </script>
</head>
<body>
    <h1>길동이의 홈페이지</h1>
    <input type="text">  <!--입력창도 새로고침됨-->
</body>

 

 

  • navigator : 실행하는 브라우저/프로그램에 대한 정보
  •  

    <script>
        for (var key in navigator){
            document.write("♣"+key+" : "+navigator[key]+"<br>");
        }
    </script>

 

 

  • history
  •  

back forward : 이전 페이지 / 다음페이지
go : 페이지 이동  ex.history.go(-1)

 

 

  • 문제 : 새로고침 버튼 누르면 배경색 변화
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BOM 응용</title>
    <style>
        body{
            width: 500px;
            margin: 20px auto;
            padding: 10px;
            background-color: rgb(255,255,255);
        }
        button{
            margin-top: 20px;
            padding: 10px 40px;
            border: 1px solid #ccc;
            background-color: rgba(253,234,234,0.6);
        }
    </style>
    <script>
        window.onload=function(){
            var r=Math.floor(Math.random()*256);
            var g=Math.floor(Math.random()*256);
            var b=Math.floor(Math.random()*256);
            document.body.style.background="rgb("+r+","+g+","+b+")";      
        }
 
        // var button=document.querySelector("#button"); => # 빼야 함 => 해결
        //     button.addEventListener("click",function(){
        //         location.reload();
        //     })  //왜 실행이 안되는지
 
        function load(){
            location.reload();
        }  //왜 onload 안에선 실행 안되는지 =>함수는 body에서 미리 호출되므로
 
 
    </script>
</head>
<body id="body">
    <p>랜덤 배경색</p>
    <p>F5 버튼 클릭할 때마다 배경색이 달라집니다</p>
    <button id="#button" onclick="load();">새로고침</button>
</body>
 
cs

 

 

  • 문제 : 1초마다 현재 시간 알려주는 팝업창
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
1. time.html
 
    <style>
        .display{
            margin-top: 20px;
            font-size: 1.8em;
            font-weight: bold;
            color: #00f;
            text-align: center;
        }
    </style>
    <script>
        //메인 홈페이지
        setInterval(function(){
            var now=new Date();
            var time=now.toLocaleTimeString();
            document.querySelector("#current").innerHTML=time;
        },1000);
    </script>
</head>
<body>
    <div id="current" class="display"></div>
</body>
 
 
2. BOM7.html
 
    <script>
        //팝업창으로 불러오기
        var popup=window.open("time.html","time","width=500, height=500");
        if (popup){
            popup.moveTo(0,0);
            popup.resizeTo(300,200);
        }else{
            alert("팝업 차단을 해제해주세요");
        }
    </script>
cs