본문 바로가기

UI/JavaScript

220923_JavaScript_국비_DOM2

<예시_1_1>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>라면 끓이는 순서</title>

</head>

<body>
    <h3>라면 끓이는 순서</h3>
    <hr>
    <ol type="A">
        <li>물을 끓인다</li>
        <li>면과 스프를 넣는다</li>
        <li>계란을 넣는다</li>
        <li><strong> 5분간</strong> 끓인다</li>
    </ol>
    <script>
        var liArray = document.getElementsByTagName("li");
        for (i = 0; i < liArray.length; i++) {
            var obj = liArray[i];
            obj.style.color = 'green';
        }
    </script>
</body>

</html>

 

↓결과

 

 

<예시_1_2>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>라면 끓이는 순서</title>

</head>

<body>
    <h3>라면 끓이는 순서</h3>
    <hr>
    <ol type="A" onclick="this.style.backgroundColor='yellowgreen'">
        <li>물을 끓인다</li>
        <li>면과 스프를 넣는다</li>
        <li>계란을 넣는다</li>
        <li><strong> 5분간</strong> 끓인다</li>
    </ol>
</body>

</html>

 

↓결과

첫화면 / ol 클릭 시 화면

 

 

<예시1_3>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>라면 끓이는 순서</title>

</head>

<body>
    <h3>라면 끓이는 순서</h3>
    <hr>
    <ol type="A" onclick="this.style.backgroundColor='yellowgreen'">
        <li>물을 끓인다</li>
        <li>면과 스프를 넣는다</li>
        <li onclick="alert(this.innerHTML)"><span>계란</span>을 넣는다</li>
        <li><strong> 5분간</strong> 끓인다</li>
    </ol>
</body>

</html>

 

↓결과

 

 

 

<예시_1_4>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>라면 끓이는 순서</title>

</head>

<body>
    <h3>라면 끓이는 순서</h3>
    <hr>
    <ol type="A" onclick="this.style.backgroundColor='yellowgreen'">
        <li>물을 끓인다</li>
        <li>면과 스프를 넣는다</li>
        <li onclick="alert(this.innerText)"><span>계란</span>을 넣는다</li>
        <li><strong> 5분간</strong> 끓인다</li>
    </ol>
</body>

</html>

 

↓결과

 

 

<예시_2>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>innerHTML 활용</title>
    <script>
        function change() {
            var p = document.getElementById("firstP");
            p.innerHTML = "<img src='../images/puppy.png'> 강아지";
        }
    </script>
</head>

<body>
    <h3>innerHTML 활용 : 아래글자를 클릭하면 사진이 보입니다</h3>
    <hr>
    <p id="firstP" style="color: green;" onclick="change()">여기를
        <span style="color: red;">클릭</span>하세요

    </p>
</body>

</html>

 

↓결과

첫화면 / 클릭 시

 

 

<예시_3>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>This test</title>
    <script>
        function change(obj, size, color){
            obj.style.color = color;
            obj.style.fontSize=size;
        }
    </script>
</head>
<body>
    <h3>this 활용</h3>
    <hr>
    <button onclick="change(this, '30px','red')">버튼1</button>
    <button onclick="change(this, '45px','blue')">버튼2</button><br>
    <hr>
    <div onclick="change(this, '35px','green')">여기를 클릭하면 크기와 색 변경</div>
</body>
</html>

 

↓결과

첫화면 / 버튼1, 버튼2, 밑에 문장 클릭 시

 

 

<예시_4>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>document.write()사용시 주의사향</title>

</head>
<body onclick="document.write('<h3>클릭되었습니다</h3>')">
    <h3>write() 잘못사용 예</h3>
    <p>
        웹 브라우저 아무곳이나 클릭해보세요
    </p>
</body>
</html>
  • HTML텍스트를 HTML 문서에 추가하기 위해 document.write()를 사용
  • HTML문서가 로드되어 출력이 모두 이루어지고 나면 document객체가 닫히기 때문에 더이상 HTML텍스트를 추가(출력)할 수 없음
    → document객체가 닫힌후 document.write()가 실행되면 현재 HTML 문서가 지워지고 새 문서가 작성되는 결과를 보여줌

 

↓결과

첫화면 / 클릭 시

 

 

<예시_5>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>visibility 프로퍼티</title>
    <style>
        span{
            visibility: hidden;
            color : green;
        }
    </style>
    <script>
        function show(){
            var objArray = document.getElementsByTagName("span");
            for(var i =0; i<objArray.length;i++){
                var obj = objArray[i];
                var style = window.getComputedStyle(obj);
                var v = style.getPropertyValue("visibility");
                if(v=="hidden")
                    obj.style.visibility = "visible";
                else    
                    obj.style.visibility="hidden";
            }
        }
    </script>
</head>
<body>
    <h3>다음 빈곳에 숨은 단어?</h3>
    <button onclick="show()">show/hide</button>
    <hr>
    <ul>
        <li>I(<span>love</span>) you</li>
        <li>CSS is Cascading
            (<span>Style</span>) Sheet.</li>
        <li>Hello (<span>world</span>)</li>
    </ul>
</body>
</html>

Window.getComputerStyle()

  • 인자로 전달받은 요소의 모든 CSS속성값을 담은 객체 회신
  • 이 속성값들은 해당 요소에 대해 활성 스타일시트와 속성값에 대한 기본 연산이 모두 반영된 결과값
  • 개별 CSS속성 값은 객체를 통해 제공되는 API 또는 CSS속성 이름을 사용해 간단히 색인화해 액세스 가능

 

↓결과

첫화면 / 버튼 클릭 시

 

 

<예시_6>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문서 동적 구성</title>
    <script>
        function createDIV(){
            var obj = document.getElementById("parent");
            var newDIV = document.createElement("div");
            newDIV.innerHTML="new DIV";
            newDIV.setAttribute("class","myDIV"); //myDIV라는 이름 부여
            newDIV.style.backgroundColor="yellow";
            newDIV.onclick=function(){
                var p_1 = this.parentElement; // 부모html태그 요소
                p_1.removeChild(this); //자신을 부모로부터 제거
            };
            obj.appendChild(newDIV);
        }
    </script>
</head>
<body id="parent">
    <h3>DIV 객체 동적 생성</h3>
    <hr>
    <p>
        DOM 트리에 동적으로 객체 삽입가능
        createElement(), appendChild(), removeChild()메소드를 이용해
        새로운 객체 생성, 삽입, 삭제하는 예제
    </p>
    <a href="javascript:createDIV()">DIV생성</a>
    
</body>
</html>

setAttribute() : 선택한 요소(element)의 속성(attribute)값을 지정

  1. 형식 : element.setAttribute('attribute_name(속성이름)', 'attribute_value(속성값)')

  2. 예시 : document.getElementById('xyz').setAttribute('title','This is title')

                 → id값이 xyz인 요소의 title속성을 This is title로 지정
                     이미 속성값이 존재한다면 그 값을 지우고 새 값 적용

 

↓결과

첫화면 / DIV생성 클릭 시(생성) / new DIV 클릭시(삭제)

 

 

<예시_7>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>document.getElementByTagName()</title>
    <script>
        function change(){
            var spanArray = document.getElementsByTagName("span");
            for (var i = 0; i<spanArray.length;i++){
                var span = spanArray[i];
                span.style.color = "red";
                span.style.fontSize="25px";
            }
        }
    </script>

</head>
<body>
    <h3>샘플문장
        <button onclick="change()">버튼</button>
    </h3>
    <hr size="5" color="green">
    Lorem ipsum <span> dolor</span> sit amet consectetur adipisicing elit.
     Temporibus, mollitia dignissimos <span> placeat</span> laboriosam dolor unde eius, 
     voluptatem, tempora dolorum itaque facere. Reprehenderit <span> hic</span> adipisci assumenda, 
    vel optio maxime dolore ea.

</body>
</html>

 

↓결과

첫화면 / 버튼 클릭 시

 

 

<예시_8>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>html 새로운 창 생성</title>
    <script>
        var win = null;
        function showHTML() {
            if (win == null || win.closed)//closed : 창이 닫혔는지 확인하는 함수
                win = window.open("", "outWin", "width=250, height=150");
            var TextArea = document.getElementById("srcText");
            win.document.open();
            win.document.write(TextArea.value);
            win.document.closed();
        }

    </script>
</head>

<body>
    <h3>HTML 새창 생성</h3>
    <hr>
    <p>
        아래에 html 문서를 작성 후 버튼 클릭
        새 윈도우에 html문서가 출력
    </p>
    <textarea id="srcText" cols="40" rows="10"></textarea>
    <br><br>
    <button onclick="showHTML()">html문서 출력하기</button>
</body>

</html>
  • 반환값 : 새로 만들어진 창 객체가 반환, 창 생성에 실패하면 null반환 → 새창 제어 가능
           형식 : var win = window.open(url, name, specs, replace);
                    - url : 새창에 보여질 주소. 선택적인 값을 비워두면 빈창(about : blank)가 보임
                    - name : 선택 / 새로 열릴 창의 속성 또는 창의 이름 지정. 기본값은 "_blank"
                    - specs : 선택 / 창의크기, 스크롤여부, 리사이즈 기능등의 속성 지정
                    - replace : 히스토리 목록에 새항목을 만들지 현재 항목을 대체할지 지정
                        true : 현재 히스토리 대체 / false : 히스토리에 새항목 지정

 

↓결과

첫화면 / 텍스트 입력 후 버튼 클릭 시

 

 

<예시_9_1>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>html태그 리스너 작성</title>

</head>
<body>
    <h3>html 태그 리스너 작성</h3>
    <hr>
    <p onmouseover="this.style.backgroundColor='green'"
    onmouseout="this.style.backgroundColor='white'">
        마우스를 올리면 green색으로 변경됨
    </p>
</body>
</html>

 

↓결과

첫화면 / 마우스 커서를 올렸을 때

 

 

<예시_9_2>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>dom객체의 이벤트 리스너 프로퍼티 함수 등록</title>
    <script>
        var p;
        function init(){ //문서가 완전히 로드되었을때 호출
            p = document.getElementById("p");
            p.onmouseover= over; //over()함수를 onmouseover리스너로 등록
            p.onmouseout = out; //out()함수를 onmouseout 리스너로 등록
        }
        function over(){
            p.style.backgroundColor = "red";
        }
        function out(){
            p.style.backgroundColor = "white";
        }
    </script>
</head>
<body onload="init()">
    <h3>dom객체의 이벤트 리스너 프로퍼티 함수 등록</h3>
    <hr>
    <p id="p">
        마우스를 올리면 red색으로 변경
    </p>

</body>
</html>

 

↓결과

첫화면 / 마우스 커서를 올렸을 때

 

 

<예시_9_3>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>익명 함수로 이벤트 리스너 작성</title>
    <script>
        var p;
        function init() { //문서가 완전히 로드되었을때 호출
            p = document.getElementById("p");

            p.onmouseover = function () {
                this.style.backgroundColor = "red";
            };
            p.addEventListener("mouseout",
                function () {
                    this.style.backgroundColor = "white"; //익명함수
                });
        }
    </script>
</head>

<body onload="init()">
    <h3>익명 함수로 이벤트 리스너 작성</h3>
    <hr>
    <p id="p">
        마우스를 올리면 red색으로 변경
    </p>
</body>

</html>

 

↓결과

첫화면 / 마우스 커서를 올렸을 때

 

 

<예시_10>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 객체 전달받기</title>

</head>
<body>
    <p id="p">
        마우스를 올려보세요
    </p>
      <!-- event는 키워드(변수가 아님) -->
    <button onclick="f(event)">클릭</button>
    <script>
        function f(e){//e는 현재 발생한 이벤트 객체
            alert(e.type); //이벤트 종류 출력
        }
    </script>
</body>
</html>

 

↓결과

첫화면 / 버튼 클릭 시

 

 

<예시_11>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 객체 프로퍼티</title>

</head>
<body>
    <h3>이벤트 객체 프로퍼티 출력</h3>
    <hr>
    <p id="p">
        버튼을 클릭하면 이벤트 객체를 출력
    </p>
    <button onclick="f(event)">클릭</button>
    <script>
        function f(e){ //e는 현재 발생한 이벤트 객체
            var text = "type : "+e.type+"<br>"
                    +"target : "+e.target+"<br>"
                    +"currentTarget : "+e.currentTarget+"<br>"
                    +"defaultPrevented : "+e.defaultPrevented;

            var p = document.getElementById("p");

            p.innerHTML=text; //이벤트 객체 프로퍼티 출력
        }
    </script>
</body>
</html>
  • 브라우저 기본 동작 : 이벤트 발생 즉시 브라우저에 의해 특정 동작을 자동으로 수행 
    예시 ) - 링크를 클릭하면 해당 url로 이동
              - 폼 전송 버튼을 클릭하면 서버에 폼이 전송
              - 마우스 버튼을 누른 채로 글자 위에서 커서를 움직이면 글자 선택
               → 기본 동작 대신 자바스크립트를 이용해 직접 구현해야하는 경우가 있음
  • 브라우저 기본 동작 막기
    event객체 사용 : event.preventDefault()메서드 사용
                                   on<event>를 사용해 할당되었다면 false를 반환해 기본동작 막기 가능
                       예시) html문서에서 링크를 클릭해도 해당 url로 이동하지 않음
                              <a href="/" onclick ="return false">이곳</a> 이나
                              <a href ="/" onclick ="event.preventDefault()">이곳을</a> 클릭
                                 → e.preventDefault는 고유 동작 중단

 

↓결과

 

 

<예시_12>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 디폴트 동작 취소</title>
    <script>
        function query(){
            var ret = confirm("네이버로 이동할까요?");
            return ret; //comfirm()의 리턴값은 true혹은 false
        }
        function noAction(e){
            e.preventDefault(); //이벤트 디폴트 동작 강제 취소
        }
    </script>
</head>
<body>
    <h3>이벤트 디폴트 동작 취소</h3>
    <hr>
     <!-- onclick=return false 는 클릭해도 링크로 이동되지 않음 -->
    <a href="http://www.naver.com" onclick="return query()">
    네이버로 이동할지 확인하는 링크</a>
    <hr>
    <form>
        <input type="checkbox">체크<br>
        <input type="checkbox" onclick="noAction(event)">체크x<br>
        
    </form>
</body>
</html>

 

↓결과

첫화면 / 링크 클릭시&nbsp; / 체는는 클릭되지만 체크x는 클릭되지 않음

 

 

<예시_13>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>계산기</title>
    <script>
        function calculate(){
            var exp = document.getElementById("exp");
            var result = document.getElementById("result");
            result.value = eval(exp.value);
        }
    </script>
</head>
<body>
    <h3>onclic 계산기 만들기</h3>
    <hr size="5" color="red">
    계산하고자 하는 수식을 입력하고 계산버튼을 누르세요
    <br><br>
    <form>
        식 : <input type="text" id="exp" value=" ">
        <input type="button" value="계산" onclick="calculate()"><br>
        결과 : <input type="text" id="result">
    </form>
</body>
</html>

 

↓결과

첫화면 / 식 입력 후 계산버튼 클릭

 

 

<예시_14>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>마우스 이벤트 객체 프로퍼티</title>
    <style>
        div {
            background-color: skyblue;
            width: 250px;
        }
    </style>
</head>

<body>
    <h3>마우스 이벤트 객체의 프로퍼티, onmousemove</h3>
    <hr>
    이미지 위에서 마우스를 움직일때 onmousemove 리스너가 실행되고,
    마우스의 위치를 보여줍니다 <br><br>
    <img src="../images/beach.png" onmousemove="where(event)">
    <div id="div"></div>
    <script>
        var div = document.getElementById("div");
        function where(e) {
            var text = "button : " + e.button + "<br>";
            text += "(screenX, screenY) : " + e.screenX + ", " + e.screenY + "<br>";//모니터상 좌표
            text += "(clientX, clientY) : " + e.clientX + ", " + e.clientY + "<br>";//브라우저상 좌표
            text += "(offsetX, offsetY) : " + e.offsetX + ", " + e.offsetY + "<br>";//이미지상 좌표
            text += "(x, y) : " + e.x + ", " + e.y + "<br>";
            div.innerHTML = text;
        }
    </script>
</body>

</html>

 

↓결과

 

 

<예시_15>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>oncontextmenu : 오른쪽 마우스 클릭 금지</title>
    <script>
        function hideMenu() {
            alert("오른쪽 클릭<컨텍스트 메뉴>금지");
            return false;
        }
        document.oncontextmenu = hideMenu;

    </script>
</head>

<body>
    <h3>oncontextmenu : 오른쪽 마우스 클릭 금지</h3>
    <hr>
    오른쪽 마우스 클릭 금지
    <br>
    <img src="../images/beach2.png">
</body>

</html>
  • 오른쪽 마우스 클릭 금지 : 오른쪽 마우스 클릭 시 팝업메뉴를 contextmenu라고 함
  • 예시) document.ondragstart = new Function('return false');
             document.onselectstart = new Function('return false');

 

↓결과

첫화면 / 오른쪽 마우스 클릭 시

 

 

<예시_16>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>random background</title>
    <script>
        function randomBackground() {
            var aaa = document.getElementById("aaa");
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            document.body.style.backgroundColor =
                "rgb(" + r + ", " + g + ", " + b + ")";
            aaa.style.color =
                "rgb(" + g + ", " + r + ", " + b + ")";
        }
    </script>
</head>

<body ondblclick="randomBackground()">
    <h3>웹브라우저 아무곳이나 더블클릭</h3>
    <hr>
    <p id="aaa">
        바탕 아무곳이나 <strong>더블클릭</strong>하면 배경색이 랜덤하게 변경
    </p>
</body>

</html>

 

↓결과

첫화면 / 더블클릭 후

 

 

<예시_17>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>window open()</title>
    <script>
        function load(URL) {
            window.open(URL, "myWin", "left=300px, top=300px, width=500px, height=400px");
        }
    </script>

</head>

<body>
    <h3>window.open()</h3>
    <hr>
    <a href="javascript:load('http://graceland.com')">
        엘비스 프레슬리 홈페이지
    </a><br><br>
    <a href="javascript:load('http://www.universalorlando.com')">
        유니버셜 올랜드 홈페이지
    </a>
</body>

</html>

 

↓결과