공부일지
231011 (HTML)
CD가참둥그렇다
2023. 10. 11. 12:28
테스트 6. 태그 이름으로 DOM 객체 찾기, getElementsByTagName()
- getElementsByTagName() : 괄호 내부의 이름을 가진 모든 태그의 요소를 가져온다. 배열의 형태로 가져온다.
<!DOCTYPE html>
<html>
<head id="myHead">
<meta charset="UTF-8">
<title>document.geElementsByTagName()</title>
<script>
function change() {
let spanArray = document.getElementsByTagName("span");
for (let i = 0; i < spanArray.length; i++) {
let span = spanArray[i];
span.style.color = "orchid";
span.style.fontSize = "20px";
}
}
</script>
</head>
<body>
<h3>
내가 좋아하는 과일
<button onclick="change()">누르세요</button>
</h3>
<hr>
저는 빨간 <span>사과</span>를 좋아해서
아침마다 한 개씩 먹고 있어요. 운동할 때는 중간 중간에
<span>바나나</span>를 먹지요. 탄수화물 섭취가 빨라
힘이 납니다. 또한 달콤한 향기를 품은 <span>체리</span>와
여름 냄새 물씬 나는 <span>자두</span>를 좋아합니다.
</body>
</html>
테스트 7. class 속성으로 DOM 객체 찾기, getElementsByClassName()
- getElementsByClassName() : 태그에 class 정보를 주어 클래스 별로 정보를 호출할 수 있다.
- 클래스는 기본적으로 중복이라고 취급하여 elements로 받아주어야 한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>document.geElementsByClassName()</title>
<script>
function viewPlace() {
let tagArray = document.getElementsByClassName("place");
for (let i = 0; i < tagArray.length; i++) {
let tag = tagArray[i];
tag.style.color = "orchid";
tag.style.fontSize = "20px";
tag.style.textDecoration = "underline"
}
}
function viewFood() {
let tagArray = document.getElementsByClassName("food");
for (let i = 0; i < tagArray.length; i++) {
let tag = tagArray[i];
tag.style.color = "darkcyan";
}
}
</script>
</head>
<body>
<h3>
가고 싶은 곳 먹고 싶은 것<br>
<button onclick="viewPlace()">가고 싶은 곳</button>
<button onclick="viewFood()">먹고 싶은 것</button>
</h3>
<hr>
<p><span class="place">제주도</span>에 가서<span class="food">흑돼지</span>를 먹고 싶고요.
<span class="place">독도</span>에 가서 <span class="food">독도 새우</span>도 먹고 싶어요. 제일 가고 싶은 곳
<span class="place">부산 자갈치 시장</span>에서 <span class="food">꼼장어 구이</span>도 먹고 싶어요</p>
</body>
</html>
테스트 10. HTML 문서 작성 연습 페이지 만들기
- 초기 상태이거나 윈도우가 닫힌 상태라면 새 창을 열어서 표시해라.
- 윈도우가 열려 있는 상태라면 기존 창에 표시해라.
- open close를 넣어야 작성한 문서를 처음부터 표시함. 누적하지 않음.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML 문서 작성기 만들기</title>
<script>
let win = null;
function showHTML() {
if (win == null || win.closed)
win = window.open("", "outSin", "width=250,height=150");
let textArea = document.getElementById("srcText");
win.document.open();
win.document.write(textArea.value);
win.document.close();
}
</script>
</head>
<body>
<h3>HTML 문서 작성기 만들기</h3>
<hr>
<p>아래에 HTML 문서를 작성하고 버튼을 클릭해 보세요.
새 윈도우에 HTML 문서가 출력됩니다.</p>
<textarea id="srcText" rows="10" cols="40"></textarea>
<br>
<br>
<button onclick="showHTML()">HTML 문서 출력하기</button>
</body>
</html>
테스트 11. HTML 문서 작성 연습 페이지 만들기
- createElemet를 사용하여 태그를 만들 수 있다.
- 만든 태그에 값을 주기 위해 .innerHTML등 다양한 요소의 값을 넣을 수 있다.
- 태그의 삭제를 위해 부모 태그의 자식 요소의 제거의 기능을 이용한다.
- appendChild를 이용하여 태그를 삽입할 위치를 지정할 수 있다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문서의 동적 굿엉</title>
<script>
function createDIV() {
let obj = document.getElementById("parent");
let newDIV = document.createElement("div");
newDIV.innerHTML = "새로 생성된 DIV입니다.";
newDIV.setAttribute("id", "myDiv");
newDIV.style.backgroundColor = "yellow";
newDIV.onclick = function(){
let p = this.parentElement;/* p에 부모 태그요소 삽입 */
p.removeChild(this);/* 부모의 자식 중 자신을 제거 */
};
obj.appendChild(newDIV);
}
</script>
</head>
<body id="parent">
<h3>DIV 객체를 동적으로 생성, 삽입, 삭제하는 예제</h3>
<hr>
<p>DOM 트리에 동적으로 객체를 삽입할 수 있습니다.
createElement(), appendChild(),
removeChild() 메소드를 이용하여 새로운 객체를 생성, 삽입, 삭제하는 예제입니다.</p>
<p><a href="javascript:createDIV()">DIV생성</a></p>
</body>
</html>
9장
테스트 3. addEventListener() 사용
- addEventListener를 만들고 (이름, 펑션)을 이용하여 기능을 만들 수 있다.
- onload = 해당 태그 읽기 완료 후 작동할 것
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addEventListener()를 이용한 리스터 등록</title>
<script>
let p;
function init() {
p = document.getElementById("p");
p.addEventListener("mouseover", over);
p.addEventListener("mouseout", out);
}
function over() {
p.style.backgroundColor="orchid";
}
function out() {
p.style.backgroundColor="white";
}
</script>
</head>
<body onload="init()">
<h3>addEventListener()를 이용한 리스너 등록</h3>
<hr>
<p id="p">마우스를 올리면 orchid 색으로 변경</p>
</body>
</html>
테스트 4. addEventListener() 사용
- function을 따로 이름을 지정하여 저장 후 추가하는 것이 아니라 해당 위치에 바로 작성할 경우 이름 없은 익명함수로 작성할 수 있다.
- addEventListener의 펑션 부분도 마찬가지로 직접 익명 함수를 직접 넣을 수 있다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>익명함수로 이벤트 리스너 등록</title>
<script>
let p;
function init() {
p = document.getElementById("p");
p.onmouseover = function() {
this.style.backgroundColor = "orchid";
}
p.addEventListener("mouseout",
function (){ this.style.backgroundColor = "white";}
);
}
</script>
</head>
<body onload="init()">
<h3>익명함수로 이벤트 리스너 등록</h3>
<hr>
<p id="p">마우스를 올리면 orchid 색으로 변경</p>
</body>
</html>
테스트 5. 이벤트 리스너에서 이벤트 객체 전달 받기
- 이벤트를 만들고 다양한 요소에서 호출할 수 있다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 객체 전달받기</title>
</head>
<body>
<p id="p">마우스를 올려보세요</p>
<button onclick="f(event)">클릭하세요</button>
<script>
function f(e) {
alert(e.type);
}
document.getElementById("p").onmouseover = f;
</script>
</body>
</html>
테스트 6. 이벤트 객체 프로퍼티 출력
- 이벤트가 발생할 때 펑션 내부에서 이벤트 객체의 정보를 받아와서 출력할 수 있다.
- type : 이벤트가 발생한 원인
- target : 이벤트가 발생한 위치
- currentTarget : 현재 이벤트가 진행중인 위치
- defaultPrevented : 기본값 false
<!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) {
let text = "type: "+e.type+"<br>"
+"target: "+e.target+"<br>"
+"currentTarget: "+e.currentTarget+"<br>"
+"defaultPrevented: "+e.defaultPrevented;
let p = document.getElementById("p");
p.innerHTML = text;
}
</script>
</body>
</html>
테스트 7. 이벤트의 디폴트 행동 취소
- onclick에 있는 return query() = query의 값이 true인지 false 인지 확인하는 과정. false로 돌아올 경우 실행되지 않는다.
- return이 들어가야 펑션의 값을 받아올 수 있다.
- preventDefault = 기본 행동이 작동하지 않게 한다. 예를 들면 링크 클릭 시 이동하는 현상
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트의 디폴트 행동 취소</title>
<script>
function query() {
let ret = confirm("네이버로 이동하시겠습니까?");
return ret;
}
function noAction(e) {
e.preventDefault();/* 이벤트의 디폴트 행동 강제 취소 */
}
</script>
</head>
<body>
<h3>이벤트의 디폴트 행동 취소</h3>
<hr>
<a href="http://www.naver.com"
onclick="return query()">네이버로 이동할 지 물어보는 링크</a>
<hr>
<form>
<input type="checkbox">빵(체크됨)<br>
<input type="checkbox" onclick="noAction(event)">술(체크 안됨)
</form>
</body>
</html>
테스트 8. 이벤트 흐름
- 캡처링 단계 – 이벤트가 하위 요소로 전파되는 단계
- 타깃 단계 – 이벤트가 실제 타깃 요소에 동작되는 단계
- 버블링 단계 – 이벤트가 상위 요소로 전파되는 단계
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 흐름</title>
</head>
<body>
<p style="color: blue">
이것은 <span style="color: red" id="span">문장입니다. </span>
</p>
<form>
<input type="text" name="s"> <input type="button" value="테스트"
id="button">
<hr>
</form>
<div id="div" style="color: green"></div>
<script>
let div = document.getElementById("div"); // 이벤트 메시지 출력 공간
let button = document.getElementById("button");
// body 객체에 캡쳐 리스너 등록
document.body.addEventListener("click", capture, true); // 켭쳐 단계(1)
// 타겟 객체에 버블 리스너 등록
button.addEventListener("click", bubble, false); // 버블 단계(2)
// body 객체에 버블 리스너 등록
document.body.addEventListener("click", bubble, false); // 버블 단계(3)
function capture(e) { // e는 이벤트 객체
let obj = e.currentTarget; // 현재 이벤트를 받은 DOM 객체
let tagName = obj.tagName; // 태그 이름
div.innerHTML += "<br>capture 단계 : " + tagName + " 태그 " + e.type
+ "이벤트";
}
function bubble(e) { // e는 이벤트 객체
let obj = e.currentTarget; // 현재 이벤트를 받은 DOM 객체
let tagName = obj.tagName; // 태그 이름
div.innerHTML += "<br>bubble 단계 : " + tagName + " 태그 " + e.type
+ "이벤트";
}
</script>
</body>
</html>
테스트 10. 마우스 관련 이벤트 리스너
- 마우스의 이벤트
- down - 클릭 중, up - 클릭을 풀 때, over - 마우스 올릴 때, out - 마우스 밖으로 보낼 때
- onwheel -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>마우스 관련 리스너</title>
<script>
let width = 1;
function down(obj) {
obj.style.fontStyle = "italic";
}
function up(obj) {
obj.style.fontStyle = "normal";
}
function over(obj) {
obj.style.borderColor = "violet";
}
function out(obj) {
obj.style.borderColor = "lightgray";
}
function wheel(e, obj) {
if (e.wheelDelta < 0) {
width--;
if (width < 0)
width = 0;
} else
width++;
obj.style.borderStyle = "ridge";
obj.style.borderwidth = width + "px";
}
</script>
</head>
<body>
<h3>마우스 관련 이벤트 리스너</h3>
<hr>
<div>마우스 관련
<span onmousedown="down(this)"
onmouseup="up(this)"
onmouseover="over(this)"
onmouseout="out(this)"
onwheel="wheel(event, this)"
style="display:inline-block">
이벤트</span>가 발생합니다.
</div>
</body>
</html>