34일차 2023-04-24

2023. 4. 24. 18:49JavaScript

Html5

 

Audio17.html

<!DOCTYPE html>
<html lang="en">
  <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>Audio17.html</title>
  </head>
  <body>
    <!--https://caniuse.com/-->
    <h2>기본 audio(src속성과 controls만 사용) 태그</h2>
    <audio src="Media/audio.mp3" controls><!--여기가 화면에 출력 controls속성때문-->
      audio태그를 지원하지 않은 브라우저입니다<br /><!--안나옴 -->
      여기를 <a href="Media/audio.mp3">클릭</a> 하세요<!--안나옴 -->
    </audio>
    <h2>audio 하위태그인 &lt;source&gt;태그 사용</h2>
    <audio controls><!--화면에 출력 controls-->
      <!--아래 중 지원하는 미디어만 재생됨.즉 하나만 재생됨-->
      <source src="Media/audio.ogg" type="audio/ogg" />
      <source src="Media/audio.mp3" type="audio/mp3" />
    </audio>
    <h2>커스텀 오디오</h2>
    <div>
      <progress value="0"></progress><!--0~1사이 숫자 넣기 1이 100%바임-->
    </div>
    <div>
      <input type="button" value="PLAY" onclick="play();" />
      <input type="button" value="PAUSE" onclick="pause();" />
      <input type="button" value="STOP" onclick="stop();" />
      &nbsp;&nbsp;<span id="current"></span> / <span id="total"></span>
    </div>
    <script>
      //Audio객체 생성]
      //var audio = new Audio();//<audio></audio>
      //audio.currentSrc="Media/audio.mp3";
      //var audio = new Audio("Media/audio.mp3");
      var audio = document.createElement("audio");
      audio.setAttribute("src", "Media/audio.mp3");
      console.log("타입:", typeof audio);
      console.log("%O", audio);
      //span객체 얻기
      var currentSpan = document.querySelector("#current");
      var totalSpan = document.querySelector("#total");
      //progress객체 얻기
      var progress = document.querySelector("progress");
      //Audio객체에 timeupdate이벤트 처리를 위한 리스너 부착
      audio.addEventListener("timeupdate", function () {
        //오디오의 총 재생시간 얻고 설정
        totalSpan.textContent = audio.duration;
        //오디오의 현재 재생시간 얻고 텍스트 설정
        currentSpan.textContent = audio.currentTime;
        //타임 업데이트에 따른 프로그레스의 진행정도 표시
        //최대값(max속성) 설정
        progress.max = audio.duration;
        //진행정도 표시
        progress.value = audio.currentTime;
      });

      function play() {
        audio.play();
      }
      var pause = function () {
        audio.pause();
      };
      function stop() {
        //stop()함수 지원안함
        //아래처럼 stop효과 기능 구현
        if (audio.played) {
          //재생중이면
          audio.currentTime = 0;
          audio.pause();
        }
      }
    </script>
  </body>
</html>

 

결과)

 


Video18.html

<!DOCTYPE html>
<html lang="en">
  <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>Video18.html</title>
  </head>
  <body>
    <h2>기본 비디오 태그</h2>

    <video src="Media/video.mp4" controls width="200" height="200">
      <!--
    <video src="Media/video.mp4" controls width="200" height="200" autoplay loop>
     -->
      video태그를 지원하지 않는 브라우저 입니다<br />
      여기를 <a href="Media/video.mp4">클릭</a> 하세요
    </video>
    <h2>video 하위태그인 &lt;source&gt;태그 사용</h2>
    <video controls width="200" height="200">
      <source src="Media/video.3gp" type="video/3gp" />
      <source src="Media/video.mp4" type="video/mp4" />
    </video>
    <h2>커스텀 비디오</h2>
    <div>
      <video
        width="300"
        height="200"
        id="video"
        src="Media/video.mp4"
        hidden
      ></video>
    </div>
    <div>
      <progress value="0"></progress>
    </div>
    <div>
      <input type="button" value="PLAY" onclick="play();" />
      <input type="button" value="PAUSE" onclick="pause();" />
      <input type="button" value="STOP" onclick="stop();" />
      <input
        type="range"
        id="volume"
        value="1"
        min="0"
        max="1"
        step="0.1"
        style="width: 80px"
      />
      &nbsp;&nbsp;<span id="current"></span> / <span id="total"></span>
    </div>
    <script>
      //비디오객체 얻기]
      var video = document.querySelector("#video");
      //span객체 얻기
      var currentSpan = document.querySelector("#current");
      var totalSpan = document.querySelector("#total");
      //progress객체 얻기
      var progress = document.querySelector("progress");
      //range 객체 얻기
      var volume = document.querySelector("#volume");
      //video객체에 timeupdate이벤트 처리를 위한 리스너 부착
      video.ontimeupdate = function () {
        //비디오의 총 재생시간 얻고 설정
        totalSpan.textContent = video.duration;
        //비디오의 현재 재생시간 얻고 텍스트 설정
        currentSpan.textContent = video.currentTime;
        //타임 업데이트에 따른 프로그레스의 진행정도 표시
        //최대값(max속성) 설정
        progress.max = video.duration;
        //진행정도 표시
        progress.value = video.currentTime;
      };

      //볼륨 조절
      //마우스를 드래그하다 놓았을때 이벤트(change)가 트리거된다
      /*
        volume.onchange=function(){
            console.log('볼륨:',volume.value);
        }*/

      volume.oninput = function () {
        console.log("볼륨:", volume.value);
        video.volume = volume.value;
      };

      function play() {
        video.hidden = ""; //비디오 보이기
        video.play();
      }
      var pause = function () {
        video.pause();
      };
      function stop() {
        //stop()함수 지원안함
        //아래처럼 stop효과 기능 구현
        if (video.played) {
          //재생중이면
          video.currentTime = 0;
          video.pause();
          video.hidden = "block"; //비디오 숨기기
        }
      }
    </script>
  </body>
</html>

 

결과)

 


Canvas19_1.html

<!DOCTYPE html>
<html lang="en">
  <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>Canvas19_1.html</title>
  </head>
  <body>
    <h2>&lt;canvas&gt;태그</h2>
    <!--※캔바스의 가로폭 세로폭은 반드시 속성으로 설정-->
    <canvas
      id="canvas"
      width="200"
      height="200"
      style="background-color: yellow"
    ></canvas>
    <script>
      var canvas = document.querySelector("#canvas");
      var ctx = canvas.getContext("2d");
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(50, 50);
      ctx.stroke();
      ctx.closePath();

      ctx.beginPath();
      ctx.lineWidth = 10;
      ctx.moveTo(50, 50);
      ctx.lineTo(100, 50);
      ctx.stroke();
      ctx.closePath();

      ctx.beginPath();
      ctx.lineWidth = 5;
      ctx.moveTo(100, 50);
      ctx.lineTo(100, 100);
      ctx.stroke();
      ctx.closePath();
      //a는 알파 즉 투명도(1에 가까울 수록 완전 불투명,0에 가까울 수록 완전투명)
      ctx.fillStyle = "rgba(255,0,0,0.5)";
      ctx.fillRect(100, 100, 50, 50);
    </script>
  </body>
</html>

 

결과)

 

 

Canvas19_2.html

<!DOCTYPE html>
<html lang="en">
  <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>Canvas19_2.html</title>
  </head>
  <body>
    <!--※캔바스의 가로폭 세로폭은 반드시 속성으로 설정-->
    <canvas
      id="canvas"
      width="200"
      height="200"
      style="background-color: yellow"
    ></canvas>
    <script>
      var canvas = document.querySelector("#canvas");
      var ctx = canvas.getContext("2d");
      ctx.font = "25px 굴림체";
      ctx.fillStyle = "blue"; //채우기 색상 설정

      //기준선 보이기]
      ctx.strokeStyle = "red"; //선 색상 설정
      ctx.moveTo(50, 20);
      ctx.lineTo(50, 180);
      ctx.stroke(); //선긋기

      //그림자 표시를 위한 설정]
      ctx.shadowColor = "rgba(192,192,192,0.8)";
      ctx.shadowOffsetX = 5;
      ctx.shadowOffsetY = 5;
      ctx.shadowBlur = 1; //최대값 100

      //글자 그리기
      ctx.textAlign = "start";
      ctx.fillText("HTML5_START", 50, 50);

      ctx.textAlign = "end";
      ctx.fillText("HTML5_END", 50, 80);

      ctx.textAlign = "center";
      ctx.fillText("HTML5_CENTER", 50, 110);

      ctx.textAlign = "left";
      ctx.fillText("HTML5_LEFT", 50, 140);

      ctx.textAlign = "right";
      ctx.fillText("HTML5_RIGHT", 50, 170);
    </script>
  </body>
</html>

 

결과)

 

 

Canvas19_3.html

<!DOCTYPE html>
<html lang="en">
  <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>Canvas19_3.html</title>
    <script>
      "use strict";
      window.addEventListener("DOMContentLoaded", function () {
        var canvas = document.querySelector("#canvas");
        var ctx = canvas.getContext("2d");
        ctx.strokeStyle = "red";
        ctx.moveTo(60, 313);
        ctx.lineTo(120, 166);
        ctx.lineTo(180, 76);
        ctx.lineTo(240, 256);
        ctx.lineTo(300, 70);
        ctx.lineTo(360, 200);
        ctx.lineTo(420, 120);
        ctx.lineTo(480, 70);
        ctx.stroke();

        //이미지 그리기용
        var canvasimg = document.querySelector("#canvasimg");
        ctx = canvasimg.getContext("2d");
        var img = new Image(); //document.createElement('img')와 같다 즉 <img/>
        img.src = "../Images/button.jpg"; //<img src='../Images/button.jpg'/>
        img.onload = function () {
          //이미지 원본 크기:drawImage(Image객체,X좌표,Y좌표);
          //ctx.drawImage(img,0,0);
          //이미지 크기 조정:drawImage(Image객체,X좌표,Y좌표,가로폭,세로폭)
          ctx.drawImage(img, 0, 0, 50, 50);
        };
      });
    </script>
  </head>
  <body>
    <canvas
      id="canvas"
      width="550"
      height="450"
      style="background-color: yellow"
    ></canvas>
    <canvas
      id="canvasimg"
      width="300"
      height="300"
      style="border: 1px green solid"
    ></canvas>
  </body>
</html>

 

결과)

Canvas19_3.html

<!DOCTYPE html>
<html lang="en">
<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>HTML5_NEW20.html</title>
</head>
<body>
    <fieldset>
        <legend>HTML5에 새롭게 추가된 요소(태그)나 속성들</legend>
        <h2>텍스트에 하이라이트 효과주는 태그(mark)</h2>
        <p>
            주요 그룹 총수들이 <mark>윤석열</mark> 대통령 미국 국빈방문 동행을 위해 23일을 전후로 출국길에<br/>
            올랐다. 최근 글로벌 <mark>경제불황</mark> 속 미국의 자국우선주의 압박까지 커가는 상황에서<br/>
            <span style="background-color: yellow;">한미동맹</span> 기반 새로운 활로를 찾는 것이 과제다.
        </p>
        <h2>진행율을 표시하는 태그(progress)</h2>
        <progress max="200" value="100" style="width:300px;height:50px"></progress>
        <h2>자동완성태그(datalist)</h2>
        <label for="keyword">검색어를 입력하세요</label>
        <input type="search" id="keyword" list="items"/>
        <datalist id="items">
            <option value="제주도"></option>
            <option value="제주공항"></option>
            <option value="제부도"></option>
            <option value="제자"></option>
            <option value="코로나"></option>
            <option value="코로나19"></option>
            <option value="코카콜라"></option>
            <option value="코알라"></option>
            <option value="HTML5"></option>
            <option value="HYBRID"></option>
        </datalist>
        <h2>이미지를 그룹화 태그(figure)</h2>
        <figure>
            <figcaption>자바이미지1</figcaption>
            <img src="../Images/java_logo.png" alt="첫번째 이미지" width="100" height="50"/>
        </figure>
        <figure>
            <figcaption>자바이미지2</figcaption>
            <img src="../Images/java_logo.png" alt="두번째 이미지" width="100" height="50"/>
        </figure>
        <h2>template태그</h2>
         <!--
        자스를 이용해서 HTML요소등을 동적으로  추가할때 템플릿으로 사용할때
        브라우저에 상에는 보이지 않은다(렌더트리에서 제외된다)
        -->
        <template>
            <li>아이템1</li>
            <li>아이템2</li>
            <li>아이템3</li>
        </template>
        <h2>새롭게 추가돤 속성들</h2>
        <h3>multiple,accept속성(type="file")</h3>
        <input type="file" multiple accept="image/png,image/jpeg"/>
        <h3>autofocus속성</h3>
        <input type="text" autofocus/>
        <h3>contenteditable속성</h3>
        <p contenteditable="true">
            주요 그룹 총수들이 <mark>윤석열</mark> 대통령 미국 국빈방문 동행을 위해 23일을 전후로 출국길에<br/>
            올랐다. 최근 글로벌 <mark>경제불황</mark> 속 미국의 자국우선주의 압박까지 커가는 상황에서<br/>
            <span style="background-color: yellow;">한미동맹</span> 기반 새로운 활로를 찾는 것이 과제다.
        </p>
        <h3>hidden속성</h3>
        <input type="button" value="버튼" hidden/>
        <h3>required속성</h3>
        <form action="https://www.nate.com">
            이름 <input type="text" name="name" required/>
            남자 <input type="radio" name="gender" value="male" required/>
            여자 <input type="radio" name="gender" value="female" required/>
            동의 <input type="checkbox" name="accept" value="OK" required/>
            <input type="submit" value="확인"/>
        </form>
        <h3>placeholder속성</h3>
        아이디 <input type="text"  placeholder="아이디 입력"/>
        비밀번호 <input type="password" placeholder="비밀번호 입력" />
    </fieldset>
</body>
</html>

결과)



JavaScript


DOM09_4.html

<!DOCTYPE html>
<html lang="en">
  <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>DOM09_4.html</title>
    <script>
      window.addEventListener("DOMContentLoaded", function () {
        var data = [
          {
            no: 2,
            title: "제목2",
            postDate: "2022-01-01",
            writer: "김길동1",
            hit: 10,
          },
          {
            no: 3,
            title: "제목 입니다",
            postDate: "2022-02-03",
            writer: "박길동2",
            hit: 5,
          },
          {
            no: 4,
            title: "내일 공약사항을 발표하겠습니다",
            postDate: "2022-05-03",
            writer: "박길동3",
            hit: 15,
          },
          {
            no: 5,
            title: "축하드립니다",
            postDate: "2022-11-15",
            writer: "박길동4",
            hit: 25,
          },
        ];
        //서버에서 데이타만 받는다고 가정하고
        //tr노드 생성후 생성된 각 노드를 추가하여 구현하지 않고
        //cloneNode()를 사용해 기존 노드 tr를 복제하여 구현하자
        //기존 노드가 없는 경우는 temlate태그 사용하자
        var tbodys = document.querySelectorAll("tbody");
        var btnDatas = document.querySelectorAll(".btnData");
        //복제할 행 얻기
        var tr = tbodys[0].querySelector("tr");

        btnDatas[0].onclick = function () {
          data.forEach((item) => {
            //기존 tr 복제:true이면 깊게 복제 즉 자식까지 모두 복제
            var clone = tr.cloneNode(true);
            //복제한 clone에서 td들 얻고 배열의 데이타로 변경
            var tds = clone.querySelectorAll("td");
            tds[0].textContent = item.no;
            tds[1].textContent = item["title"];
            tds[2].textContent = item.postDate;
            tds[3].textContent = item["writer"];
            tds[4].textContent = item.hit;
            //console.log(clone);
            //tbodys[0].append(clone);//혹은 insertAdjacentElement()사용
            //tbodys[0].insertAdjacentElement('beforeend',clone);//혹은
            //tr.insertAdjacentElement('afterend',clone);//역순으로
            tr.insertAdjacentElement("afterend", clone);
            tr = clone; //기존 tr을 clone로 변경-역순이 아닌 순서대로
          });
        }; //onclick

        //복제할 행이 없는 경우
        var template = document.querySelector("template");
        //console.log(template);
        //console.log('%O',template);//template요소의 하위요소들을 가져올때는 content속성으로
        console.log(template.content);
        btnDatas[1].onclick = function () {
          data.forEach(function (item) {
            //현재 DOM가 아닌 외부 DOM의 노드를 복사하여 현재 DOM에 넣을 수 있도록 해줍니다.
            //여기서 외부 DOM이란 예를들면 iframe을 구성하는 문서의 노드 혹은 temlate태그로 구성한 노드
            var clone = document.importNode(template.content, true);
            //복제한 clone에서 td들 얻고 배열의 데이타로 변경
            var tds = clone.querySelectorAll("td");
            tds[0].textContent = item.no;
            tds[1].textContent = item["title"];
            tds[2].textContent = item.postDate;
            tds[3].textContent = item["writer"];
            tds[4].textContent = item.hit;
            //console.log(clone);
            tbodys[1].append(clone);
          });
        };
      });
    </script>
  </head>
  <body>
    <input
      type="text"
      placeholder="페이지 혹은 데이타 교체 테스트용"
      style="width: 60%"
    />
    <h2>DOM API 사용하기:노드복제 하기</h2>
    <fieldset>
      <legend>데이타 뿌려주기(복제할 행이 있는 경우)</legend>

      <input type="button" class="btnData" value="데이타 넣기" />
      <hr />
      <table
        style="
          text-align: center;
          background-color: black;
          border-spacing: 1px;
          width: 70%;
        "
      >
        <thead>
          <tr style="background-color: white">
            <th style="width: 5%">번호</th>
            <th>제목</th>
            <th style="width: 15%">작성일</th>
            <th style="width: 15%">작성자</th>
            <th style="width: 8%">조회수</th>
          </tr>
        </thead>
        <tbody>
          <tr style="background-color: white">
            <td>1</td>
            <td style="text-align: left">제목1</td>
            <td>2022-09-01</td>
            <td>가길동</td>
            <td>20</td>
          </tr>
        </tbody>
      </table>
    </fieldset>
    <fieldset>
      <legend>데이타 뿌려주기(복제할 행이 없는 경우)</legend>
      <input type="button" class="btnData" value="데이타 넣기" />
      <hr />
      <template>
        <tr style="background-color: white">
          <td>1</td>
          <td style="text-align: left">제목1</td>
          <td>2022-09-01</td>
          <td>가길동</td>
          <td>20</td>
        </tr>
      </template>
      <table
        style="
          text-align: center;
          background-color: black;
          border-spacing: 1px;
          width: 70%;
        "
      >
        <thead>
          <tr style="background-color: white">
            <th style="width: 5%">번호</th>
            <th>제목</th>
            <th style="width: 15%">작성일</th>
            <th style="width: 15%">작성자</th>
            <th style="width: 8%">조회수</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </fieldset>
  </body>
</html>

 

결과) 복제할 행이 있는 경우 (데이타 넣기 3번 누름)

추가) 복제할 행이 없는 경우(데이타 넣기 3번 누름)

 

DOM09_5.html

<!DOCTYPE html>
<html lang="en">
  <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>DOM09_5.html</title>
    <script>
      //태그명으로 얻기-체크한 값과 입력값을 콘솔에 출력하기
      function fnGetElementsByTag() {
        var inputs = document.getElementsByTagName("input");
        console.log("%O", inputs); //▶ HTMLCollection(11)(유사배열) :length속성,item()함수
        //var inputs = document.querySelectorAll('input');
        //console.log('%O',inputs);//▶ NodeList(11)(유사배열) :length속성,item()함수,entries()함수,forEach()함수,keys()함수,values()함수....
        //console.log(inputs.item(0).value);
        //console.log(inputs.item(0).checked);
        console.log(inputs[0].value);
        console.log(inputs[0].checked);
        //유사배열은 배열처럼 사용[o]
        //for(var i=0; i < inputs.length;i++) console.log(inputs[i]);
        //inputs.forEach(function(item){});//[x]forEach is not a function
        //[유사배열에 forEach적용하기]
        //방법1:유사배열을 배열로 만들기:Array.from()
        //Array.from(inputs).forEach(function(item){console.log(item);})
        //방법2:유사배열의 프로토타입에 배열의 forEach 추가
        HTMLCollection.prototype.forEach = Array.prototype.forEach;
        //inputs.forEach(function(item){console.log(item);});

        var checkString = "",
          textString = "";
        inputs.forEach(function (item) {
          /* ※자스에서 checked속성의 체크 여부 판단시에는 true혹은 false로 판단*/

          if (item.name === "inter" && item.checked === true) {
            checkString += codeToValue(item.value) + " ";
          }
          if (item.name === "txt") textString = item.value;
        });
        console.log("체크된 값:", checkString);
        console.log("입력한 값:", textString);
      } /////////////////
      function codeToValue(code) {
        switch (code.toUpperCase()) {
          case "POL":
            return "정치";
          case "ECO":
            return "경제";
          default:
            return "연예";
        }
      } //////////////////
      //name속성으로 얻기 -체크된서는 체크해제,체크 안된거는 체크
      function fnGetElementsByName() {
        var names = document.getElementsByName("inter");
        console.log("%O", names); //▶ NodeList(3)
        //keys():{'value':인덱스,done:boolean}형태의 객체반환
        //       value는 NodeList에 저장된 요소들의 인덱스
        //       done는 꺼내올 요소가 있으면 false,없으면 true
        //       즉 배열의 키라 할수 있는 인덱스를 꺼내 올수 있다
        var iterator = names.keys();
        console.log("%O", iterator);
        /*
            console.log(iterator.next());//{value: 0, done: false}
            console.log(iterator.next());//{value: 1, done: false}
            console.log(iterator.next());//{value: 2, done: false}
            console.log(iterator.next());//{value: undefined, done: true}*/
        var index;
        while ((index = iterator.next().value) !== undefined) {
          console.log(names[index]);
        }
        //values():{'value':노드,done:boolean}형태의 객체반환
        //       value는 NodeList에 저장된 노드들
        //       done는 꺼내올 요소가 있으면 false,없으면 true
        var iterator_ = names.values(); //반환타입:IterableIterator<HTMLElement> 즉 HTML요소(태그)
        /*
            console.log(iterator_.next());//{value: input, done: false}
            console.log(iterator_.next());//{value: input, done: false}
            console.log(iterator_.next());//{value: input, done: false}
            console.log(iterator_.next());//{value: undefined, done: true}*/
        var node;
        while ((node = iterator_.next().value) !== undefined) {
          console.log(node);
        }

        //자스로 체크 설정시에는 checked="checked" 나 checked=true;
        //자스로 체크 해제시에는 checked=null 나 checked=false;
        //단,조건 판단시에는 반드시 true나 false 로 판단해야 된다.
        names.forEach(function (item) {
          if (item.checked) item.checked = false;
          else item.checked = true;
        });
      } ////////////
      //클래스명으로 얻기-시작태그와 종료태그사이의 컨텐츠 읽어오기
      function fnGetElementsClass() {
        var portals = document.getElementsByClassName("portal");
        console.log("%O", portals); //▶ HTMLCollection(3)
        for (var i = 0; i < portals.length; i++) {
          console.log(portals[i].textContent);
        }
      } ////////////////////

      //아이디명으로 얻기1
      function fnChangeImage(num) {
        var img = document.getElementById("image");
        //img.setAttribute('src','../Images/'+num+'.jpg');
        img.src = "../Images/" + num + ".jpg";
      }
      //아이디명으로 얻기2
      function fnCopy() {
        document.getElementById("dest").value =
          document.getElementById("src").value;
        document.getElementById("destTxt1").value =
          document.getElementById("srcTxt1").value;
        document.getElementById("destTxt2").value =
          document.getElementById("srcTxt2").value;
      }
    </script>
  </head>
  <body>
    <h2>DOM API 사용하기:노드 가져오기</h2>
    <fieldset style="width: 60%">
      <legend>다양한 방법으로 노드 가져오기</legend>
      <h2>태그명으로 얻기</h2>
      <input type="checkbox" name="inter" value="POL" />정치
      <input type="checkbox" name="inter" value="ECO" />경제
      <input type="checkbox" name="inter" value="ENT" checked />연예
      <input type="text" name="txt" />
      <input
        type="button"
        value="태그명으로 DOM객체 얻기"
        onclick="fnGetElementsByTag()"
      />
      <h2>태그의 name속성으로 얻기</h2>
      <input
        type="button"
        value="NAME속성에 지정한 값으로 DOM객체 얻기"
        onclick="fnGetElementsByName()"
      />

      <h2>클래스명으로 얻기</h2>
      <ul>
        <li><a href="#" class="portal">네이버</a></li>
        <li><a href="#" class="portal">다음</a></li>
        <li><a href="#" class="portal">네이트</a></li>
      </ul>
      <button onclick="fnGetElementsClass()">
        클래스명으로 DOM객체 얻어오기
      </button>
      <h3>아이디명으로 얻기</h3>
      <fieldset>
        <legend>이미지 교체</legend>
        <a href="javascript:fnChangeImage(1)">1번 이미지</a>
        <a href="javascript:fnChangeImage(2)">2번 이미지</a>
        <a href="javascript:fnChangeImage(3)">3번 이미지</a>
        <a href="javascript:fnChangeImage(4)">4번 이미지</a>
        <hr />
        <img
          id="image"
          src="../Images/3.jpg"
          alt="이미지교체"
          style="width: 200px; height: 200px"
        />
      </fieldset>
      <fieldset>
        <legend>전화번호 복사</legend>
        <select id="src">
          <option value="010">010</option>
          <option value="011">011</option>
          <option value="017">017</option>
          <option value="019">019</option>
        </select>
        -
        <input type="text" size="4" maxlength="4" id="srcTxt1" />
        -
        <input type="text" size="4" maxlength="4" id="srcTxt2" />
        <br />
        <input type="button" value="복사" onclick="fnCopy()" />
        <br />
        <select id="dest">
          <option value="010">010</option>
          <option value="011">011</option>
          <option value="017">017</option>
          <option value="019">019</option>
        </select>
        -
        <input type="text" size="4" maxlength="4" id="destTxt1" />
        -
        <input type="text" size="4" maxlength="4" id="destTxt2" />
      </fieldset>
    </fieldset>
  </body>
</html>

 

결과) 태그명으로 얻기 (정치, 경제 선택 입력:333 태그명으로 DOM객체 얻기 클릭 시

 

결과) name속성으로 얻기) 정치, 경제 선택 후 NAME속성에 지정한 값으로 DOM객체 얻기 클릭 시

정치, 경제 선택 후
선택된거 스위칭
두가지 방법으로 해서 결과 값2번씩

결과) 클래스명으로 얻기

결과) 아이디명으로 얻기 (이미지 선택시 사진이 변경됨)

결과) 전화번호 복사 (복사 클릭시 아래 빈칸이 복사됨)

 

 

 

 

 

 

 

'JavaScript' 카테고리의 다른 글

36일차 2023-04-26  (0) 2023.04.26
35일차 2023-04-25  (0) 2023.04.25
33일차 2023-04-21  (0) 2023.04.21
32일차 2023-04-20  (1) 2023.04.20
31일차 2023-04-19  (0) 2023.04.19