본문 바로가기

UI/JavaScript

220927_JavaScript_국비_BOM2

<예시_1>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>브라우저 정보 출력</title>
    <style>
        span {
            color: blue;
        }

        div {
            border-color: yellow;
            border-style: solid;
            padding: 5px;
        }
    </style>
    <script>
        function printNavigator() {
            var text = "<span>appCodeName</span> : " + navigator.appCodeName + "<br>";
            text += "<span>appName</span> : " + navigator.appName + "<br>";
            text += "<span>appVersion</span> : " + navigator.appVersion + "<br>";
            text += "<span>platform</span> : " + navigator.platform + "<br>";
            text += "<span>product</span> : " + navigator.product + "<br>";
            text += "<span>userAgent</span> : " + navigator.userAgent + "<br>";
            text += "<span>vendor</span> : " + navigator.vendor + "<br>";
            text += "<span>language</span> : " + navigator.language + "<br>";
            text += "<span>onLine</span> : " + navigator.onLine + "<br>";
            text += "<span>cookieEnavled</span> : " + navigator.cookieEnabled + "<br>";
            text += "<span>javaEnabled</span> : " + navigator.javaEnabled + "<br>";
            text += "<span>plugins.length</span> : " + navigator.plugins.length + "<br>";
            for (j = 0; j < navigator.length; j++) {
                text += "plugins" + j + " :<blockquote>";
                text += navigator.plugins[j].name + "<br>";
                text += "<i>" + navigator.plugins[j].description + "</i><br>";
                text += navigator.plugins[j].filename + "</blockquote>";
            }
            //div 태그에 출력
            var div = document.getElementById("div");
            div.innerHTML = text;
        }
    </script>
</head>

<body onload="printNavigator()">
    <h3>브라우제 관한 정보 출력</h3>
    아래 이 브라우저에 관한 여러 정보를 출력합니다
    <hr>
    <p>
    <div id="div"></div>
    </p>

</body>

</html>

 

↓결과

 

 

<예시_2>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>스크린에 관한 정보 출력</title>
    <script>
        function printScreen() {
            var text = "availHeight: " + screen.availHeight + "<br>";
            text += "availWidth: " + screen.availWidth + "<br>";
            text += "colorDepth: " + screen.colorDepth + "<br>";
            text += "pixelDepth: " + screen.pixelDepth + "<br>";
            text += "height: " + screen.height + "<br>"; //화면의 해상도
            text += "width: " + screen.width + "<br>";
            document.getElementById("div").innerHTML = text;
        }
    </script>

</head>

<body onload="printScreen()">
    <h3>스크린에 관한 정보</h3>
    <hr>
    <div id="div"></div>

</body>

</html>

 

↓결과

 

 

<예시_3_1>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>산수</title>
    <style>
        td {
            padding-left: 10px;
            padding-right: 10px;
        }
    </style>
    <script>
        function calc() {
            var total = 0;
            var qArray = document.getElementsByClassName("question");
            var aArray = document.getElementsByClassName("answer");
            for (i = 0; i < qArray.length; i++) {
                var question = qArray[i].innerHTML;
                var correctAnswer = eval(question);
                var userAnswer = aArray[i].value;
                if (userAnswer == "" || isNaN(userAnswer)) {//답이 없거나 문자가 입력된 경우
                    total += 0;
                    qArray[i].style.textDecoration = "line-through";
                } else if (parseInt(userAnswer) == correctAnswer) { //답이 일치하는 경우
                    total += 1;
                    qArray[i].style.textDecoration = "none";//이전에 틀리 문제에 다시 답을 하고 채점버튼을 누르는 경우를 위해
                } else {//답이 틀린 경우
                    total += 0;
                    qArray[i].style.textDecoration = "line-through";
                }
            }
            document.getElementById("score").innerHTML = total;
        }
    </script>
</head>

<body>
    <h3>문제 풀기</h3>
    수식을 계산하여 답을 입력하고 채점버튼을 눌러주세요
    <hr>
    <form>
        <table>
            <tr>
                <td class="question">5*6</td>
                <td><input type="text" class="answer" size="8"></td>
            </tr>
            <tr>
                <td class="question">5+1-8</td>
                <td><input type="text" class="answer" size="8"></td>
            </tr>
            <tr>
                <td class="question">5*6/2</td>
                <td><input type="text" class="answer" size="8"></td>
            </tr>
            <tr>
                <td class="question">4/2+45</td>
                <td><input type="text" class="answer" size="8"></td>
            </tr>
            <tr>
                <td>
                    <button type="button" onclick="calc()">제출</button>
                </td>
                <td><span id="score">0</span></td>

            </tr>
        </table>
    </form>
</body>

</html>

 

↓결과

 

 

<예시_3_2>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>산수를 풀어 봅시다</title>
    <style>
        td {
            padding-left: 10px;
            padding-right: 10px;
        }
    </style>
    <script>
        function calc() {
            var total = 0;
            var qArray = document.getElementsByClassName("question");
            var aArray = document.getElementsByClassName("answer");
            for (i = 0; i < qArray.length; i++) {
                var question = qArray[i].innerHTML;
                var correctAnswer = Math.floor(eval(question));
                var userAnswer = aArray[i].value;
                if (userAnswer == "" || isNaN(userAnswer)) {//답이 없거나 문자가 입력된 경우
                    total += 0;
                    qArray[i].style.textDecoration = "line-through";
                }
                else if (parseInt(userAnswer) == correctAnswer) { //답이 맞는 경우
                    total += 1;
                    qArray[i].style.textDecoration = "none"; //혹시 이전에 틀린 문제에 다시 답을 하고 채점 버튼을 누르는 경우를 위해
                }
                else { //답이 틀린 경우
                    total += 0;
                    qArray[i].style.textDecoration = "line-through";
                }
            }
            document.getElementById("score").innerHTML = total;
        }
        function makeExpresstion() {
            var qArray = document.getElementsByClassName('question');
            var aArray = document.getElementsByClassName('answer');
            for (i = 0; i < qArray.length; i++) {
                var number1 = Math.floor(Math.random() * 20) + 1;
                var number2 = Math.floor(Math.random() * 20) + 1;//0이 될 수 없음
                var op = Math.floor(Math.random() * 4);
                var operator = "+"; //디폴트 값
                switch (op) {
                    case 0: operator = "+"; break;
                    case 1: operator = "-"; break;
                    case 2: operator = "*"; break;
                    case 3: operator = "/"; break;
                }
                qArray[i].innerHTML = number1 + operator + number2;
                qArray[i].style.textDecoration = "none";

                aArray[i].value = "";//답 입력란 지우기
                document.getElementById("score").innerHTML = 0;//맞은 문항 수 지우기
            }
        }
    </script>
</head>
<!-- 수식이 만들어짐 -->

<body onload="makeExpresstion()">
    <h3>산수 문제를 풀어 봅시다.</h3>
    자동으로 문제가 만들어집니다. 답 입력 후 채점 버튼을 누르세요.
    다시버튼을 누르면 새로운 문제가 출력됩니다.(단, 나누기 결과는 정수입니다)
    <hr>
    <form>
        <table>
            <tr>
                <td class="question"></td>
                <td><input class="answer" type="text" size="8"></td>
            </tr>
            <tr>
                <td class="question"></td>
                <td><input class="answer" type="text" size="8"></td>
            </tr>
            <tr>
                <td class="question"></td>
                <td><input class="answer" type="text" size="8"></td>
            </tr>
            <tr>
                <td class="question"></td>
                <td><input class="answer" type="text" size="8"></td>
            </tr>
            <tr>
                <td><button type="button" onclick="calc()">채점</button></td>
                <td><span id="score">0</span>&nbsp;&nbsp;&nbsp;&nbsp;
                    <button type="button" onclick="makeExpresstion()">다시</button>
                </td>
            </tr>
        </table>
    </form>
</body>

</html>

 

↓결과

 

 

<예시_4>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>screen객체</title>
    <script>
        function checkScreen() {
            if (screen.width < 2200 || screen.height < 1024)
                alert("스크린 해상도가 낮습니다");
        }
    </script>
</head>

<!-- onload시 함수를 호출 했기때문에 첫화면에 경고창이 뜸 -->
<body onload="checkScreen()">
    <h3>screen객체</h3>
    <hr>
    <p>
        스크린의 해상도가 2280*1024보다 낮은 경우
        웹 페이지가 정상적으로 출력되지 않을 수 있음을 알리는 경고를 출력합니다
    </p>

</body>

</html>

 

↓결과

 

 

<예시_5>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>getElementById</title>
    <script>
        function process1() {
            var ob = document.getElementById("txt").value;
            document.getElementById("view1").innerText = ob;
            document.getElementById("txt").value = "";
        }
    </script>

</head>

<body>
    <input type="text" id="txt" size="20" name="text">
    <input type="button" value="출력1" onclick="process1()">
    <br><br><br>
    <div id="view1"></div>
</body>

</html>

 

↓결과

텍스트값 입력 후 출력1버튼 클릭 시

 

 

<예시_6>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>표준 이벤트 모델</title>
    <style>
        #box {
            background-color: orange;
            border: 1px solid;
            padding: 5px;
            color: white;
            width: 300px;
            height: 200px;
        }
    </style>
</head>

<body>
    <div id="box">
        <button onclick="addEventHandler()" id="startbtn">시작</button>
        <button onclick="removeHandler()" id="stopbtn">정지</button>
    </div>
    <p id="demo"></p>
    <script>
        function myFunction() {
            document.getElementById("demo").innerHTML = "x좌표 : " + event.x
                +"&nbsp;&nbsp;&nbsp;y좌표 : " + event.y;
        }
        function addEventHandler() {
            document.getElementById("box").addEventListener("mousemove", myFunction); //이벤트 추가
        }
        function removeHandler() {
            document.getElementById("box").removeEventListener("mousemove", myFunction)//이벤트 제거
            //addEventListener()를 사용해 이벤트를 추가한 경우
            //반대로 이를 제거할 수 있으며 이때 removeEventListener()를 사용
        }

    </script>
</body>

</html>

 

↓결과

 

 

<예시_7>

test.html 파일 생성)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>history 객체</title>
    <script>
        document.write("방문한 페이지 수 : " + history.length);
    </script>
</head>

<body>
    <h3>history객체 (첫번째 페이지)</h3>
    <a href="test1.html">다음페이지</a><br><br>
    <input type="button" value="이전으로_1" onclick="javascript:history.back()">
    <input type="button" value="다음으로_1" onclick="history.forward()">
    <input type="button" value="처음으로_1" onclick="history.go(-2)">
</body>

</html>

 

test1.html 파일 생성)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>history객체</title>
    <script>
        document.write("방문한 페이지 수 : " + history.length);
    </script>
</head>

<body>
    <h3>history객체 연습(두번째 페이지)</h3>
    <a href="test2.html">다음페이지</a><br><br>
    <input type="button" value="이전으로_2" onclick="javascript:history.back()">
    <input type="button" value="다음으로_2" onclick="history.forward()">
    <input type="button" value="처음으로_2" onclick="history.go(-2)">
</body>

</html>

 

test2.html 파일 생성)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>history객체</title>
    <script>
        document.write("방문한 페이지 수 : " + history.length);
    </script>
</head>

<body>
    <h3>history객체 연습(세번째 페이지)</h3>
    <input type="button" value="이전으로_3" onclick="javascript:history.back()">
    <input type="button" value="다음으로_3" onclick="history.forward()">
    <input type="button" value="처음으로_3" onclick="history.go(-2)">
</body>

</html>

 

↓결과

첫화면 / 다음페이지 클릭 시

 

 

<예시_8>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>사이트 접속</title>
    <script>
        function loadSite(select) {
            var index = select.selectedIndex;
            var site = select.options[index].value;
            window.open(site, "", "left=500,top=400,width=500,height=400");
        }
    </script>
</head>

<body>
    <h3>옵션 선택으로 사이트 접속</h3>
    옵션 선택마다 새 윈도우에 접속합니다
    <hr>
    <form>
        <p>접속 할 사이트</p>
        <select onchange="loadSite(this)">
            <option value="http://www.daum.net">다음</option>
            <option value="http://www.naver.com">네이버</option>
            <option value="http://www.google.com">구글</option>
        </select>
    </form>
</body>

</html>

 

↓결과

 

 

<예시_9>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>html5 학습하는 사이트</title>
    <script>
        function printWelcome() {
            var newWin = window.open("", "", "width=200, height=80");
            newWin.document.write("접속");
            newWin.document.close();
        }
    </script>
</head>

<body onload="printWelcome()">
    <h3>html5</h3>
    <hr>
    <p>
        html5학습하는 사이트입니다
    </p>

</body>

</html>

 

↓결과

 

 

<예시_10>

win_1.html 파일 생성)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>setTimeout()</title>

</head>

<body bgcolor="pink">
    hello <br>
    world

</body>

</html>

 

js_10.html 파일 생성)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>window 객체</title>
    <script>
        window.onload = function () {
            var win = window.open('win_1.html', '', 'width=300,height=200');
            win.moveTo(100, 100);

            window.setTimeout(function () { win.close(); }, 5000)
            // setTimeout() : 코드를 바로 실행하지 않고 일정 시간을 기다린 후 실행해야하는 경우
            //첫번째 인자로 실행할 코드, 두번째 인자로 지연시간 밀리초(ms)단위로 받음
        }
    </script>

</head>

<body>
    <hr size="5" color="red">
    setTimeout test <br>
    setTimeout test <br>
    setTimeout test <br>
    <hr size="5" color="green">

</body>

</html>

 

↓결과

5초 후 win_1.html 파일은 사라짐

 

 

<예시_11>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>setTImeout()으로 웹 페이지 자동 연결</title>

</head>

<body>
    <h3>이미지에 마우스를 올리고 3초간 그대로 있을때 사이트로 이동</h3>
    <hr>
    <img id="img" src="../images/naver.gif" onmouseover="startTimer(3000)" onmouseout="cancelTimer()">
    <script>
        var timerID = null;
        function startTimer(time) {
            //타이머 시작
            timerID = window.setTimeout("load('http://www.naver.com')", time);

            //툴팁 메시지
            document.getElementById("img").title = "타이머 작동 시작";
        }
        function cancelTimer() {
            if (timerID != null) {
                window.clearTimeout(timerID);//타이머 중단
            }
        }
        function load(url) {
            window.location = url;//현재 윈도우에 url사이트 로드
        }
    </script>
</body>

</html>

 

↓결과

 

 

<예시_12>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>location 개체</title>
    <script>
        var t = new Date();
        document.write(t.getHours() + " : " + t.getMinutes() + " : " + t.getSeconds());

        setInterval(function () {
            location.reload();//현재 문서 리로드하는 방법
        }, 1000);
        // setInterval() : 어떤 코드를 일정한 시간 간격을 두고 반ㄴ복해서 실행할때
        //예 : 특정부분 주기적으로 업데이트, API로 부터 변경된 데이터를 주기적으로 받는 경우
        document.write("<br>현재 문서 주소 : " + location.href);

        console.log(location.toString(), location.href);

        document.write("<br> 현재 문서 호스트 이름 : " + location.hostname);
        document.write("<br> 현재 문서 파일 경로명 : " + location.pathname);

    // Location : 문서의 주소와 관련된 객체, window객체 프로퍼티
    //윈도우의 문서 url변경가능, 문서 위치와 관련된 다양한 정보 확인가능
    </script>
</head>

<body>

</body>

</html>

 

↓결과

 

 

<예시_13>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>setTimeout() / clearTimeout()</title>
    <style>
        div {
            display: inline-block;
            width: 7em;
            border: 2px solid darkblue;
            background-color: aliceblue;
        }
    </style>
    <script>
        function startClock() {
            var clock = document.getElementById("clock");
            timeout(clock);
        }
        function timeout(obj) {
            var current = new Date();
            obj.innerHTML = current.toLocaleTimeString()
            setTimeout("timeout(clock)", 1000);//1초 후 timeout()호출
            //setTimeout : 일정시간이 지난 후에 함수를 실행하는 방법
        }
    </script>
</head>

<body onload="startClock()">
    <h3>div태그에 시계 만들기</h3>
    <hr size="5" color="red">
    <div id="clock"></div>

</body>

</html>

 

↓결과

 

<예시_14>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>setInterval()로 텍스트 회전</title>

</head>

<body>
    <h3>텍스트가 자동 회전하며 마우스로 클릭하면 중단</h3>
    <hr>
    <div>
        <span id="span" style="background-color: yellow;">
            hello world</span>
    </div>
    <script>
        var span = document.getElementById("span");
        var timerID = setInterval("doRotate()", 200);//200ms 주기로 doRotate()호출

        var flag = true;
        if (flag) {
            span.onclick = function (e) {//마우스 클릭 이벤트 리스너
                clearInterval(timerID);//타이머 해제, 문자열 회전 중단
                flag = false;
            }
        } else {
            timerID = setInterval("doRotate()", 200);
            flag = true;
        }
        function doRotate() {
            var str = span.innerHTML;
            var firstChar = str.substr(str.length - 1, 1);//마지막글자를 뽑아서 첫번째 글자로
            var remains = str.substr(0, str.length - 1); //마지막글자는 제외됨
            str = firstChar + remains;
             //반대로 돌아감
            //var firstChar = str.substr(0, 1);//첫글자를 뽑아서 맨뒤에 붙인다
            //var remains = str.substr(1, str.length - 1);//두번째 글자부터 마지막글자까지
            //str = remains + firstChar;

            span.innerHTML = str;//str 텍스트를 span객체에 출력
        }
    </script>
</body>

</html>

 

↓결과

 

 

<예시_15>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>웹페이지의 자동 스크롤</title>
    <script>
        function startScroll(interval) {
            setInterval("autoScroll()", interval);
        }
        function autoScroll() {
            scrollBy(0, 10);//10픽셀 위로 스크롤,마이너스값을 쓰면 아래서 위로 스크롤
        }
    </script>
</head>

<body onload="startScroll(1000)">
    <h3>자동 스크롤 페이지</h3>
    <hr>
    Lorem ipsum dolosit <br>
    amet consectetur adipisicing elit. <br>
    Dolore est consequuntur <br>
    temporibus harum rem, <br>
    odio molestiae ut unde <br>
    voluptatum aperiam magni <br>
    error iste repellat voluptatibus <br>
    aliquid fuga eos alias. <br>
    Lorem ipsum dolosit <br>
    amet consectetur adipisicing elit. <br>
    Dolore est consequuntur <br>
    temporibus harum rem, <br>
    odio molestiae ut unde <br>
    voluptatum aperiam magni <br>
    error iste repellat voluptatibus <br>
    aliquid fuga eos alias. <br>
</body>

</html>
  • scrollBy(가로 스크롤 값, 세로 스크롤바) : 상대적 위치, 현재위치기준으로 파라미터 값으로 넘겨준만큼 이동
    예시) scrollBy(100,100) : 현재 스크롤 위치에서 x스크롤을 100만큼, y 크르롤 100만큼 이동
  • scrollTo(가로 스크롤 위치값, 세로 스크롤위치값) : 절대적 위치, 왼쪽 모서리부터 시작해 전체 스크롤 값을 기준으로
                                                                   파라미터로 넘겨준값으로 이동 , 현재 위치가 아닌 상단 모서리 기준
  • → 차이점 : 기준점, 절대적인지 상대적인지

↓결과

창 크기를 줄이면 자동으로 스크롤됨

 

↓결과

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>웹 페이지 프린트</title>

</head>

<body>
    <h3>웹 페이지 프린트</h3>
    <hr>
    <p>
        window객체의 print()메소드를 호출하면
        indow객체에 담겨 있는 웹 페이지가 프린트 됩니다
    </p>
    <a href="javascript:window.print()">이곳을 누르면 프린트 됩니다</a>
    <div id="logoDiv">
        <img src="../images/apple.png" alt="apple">
    </div>
    <p>
        <input type="button" value="프린트" onclick="print()">
    </p>
</body>

</html>

 

↓결과